xxxxxxxxxx
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>D3 v4 - force layout</title>
<style>
html, body, #graph {
width: 900px;
height: 500px;
}
</style>
</head>
<body>
<div id="graph"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script>
<script>
!(function(){
"use strict"
var width,height
var chartWidth, chartHeight
var margin
var svg = d3.select("#graph").append("svg")
// var chartLayer = svg.append("g").classed("chartLayer", true)
console.log('svg', svg);
main()
function main() {
var range = 10
var data = {
nodes:d3.range(0, range).map(function(d){ return {label: "l"+d ,r:~~d3.randomUniform(8, 28)()}}),
}
console.log('data', data);
console.log(d3.range(0, range).map(function(d){ return {label: "l"+d ,r:~~d3.randomUniform(8, 28)()}}));
// setSize(data)
drawChart(data)
}
// function setSize(data) {
// width = document.querySelector("#graph").clientWidth
// height = document.querySelector("#graph").clientHeight
// console.log('width', width);
// console.log('height', height);
// margin = {top:0, left:0, bottom:0, right:0 }
// chartWidth = width - (margin.left+margin.right)
// chartHeight = height - (margin.top+margin.bottom)
// svg.attr("width", width).attr("height", height)
// }
function drawChart(data) {
chartWidth = 900
width = 900
height = 500
svg.attr("width", width).attr("height", height)
var simulation = d3.forceSimulation()
.force("collide",d3.forceCollide( function(d){return d.r + 8 }).iterations(16) )
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(chartWidth / 2, chartWidth / 2))
.force("y", d3.forceY(0))
.force("x", d3.forceX(0))
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(data.nodes)
.enter().append("circle")
.attr("r", function(d){ return d.r })
var ticked = function() {
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
simulation
.nodes(data.nodes)
.on("tick", ticked);
}
}());
</script>
</body>
</html>
https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js