var width = 700,
height = 300;
var data = [{"name":"河北","val":"62356"},
{"name":"河南","val":"89565"},
{"name":"广东","val":"63658"},
{"name":"江西","val":"68525"},
{"name":"上海","val":"36585"},
{"name":"广西","val":"66589"},
{"name":"云南","val":"86955"},
{"name":"江苏","val":"75565"},
{"name":"陕西","val":"73668"},
{"name":"湖南","val":"95684"}
]
//range(节点数目),radius大小
var nodes = d3.range(10).map(function(i) {
var data1 = {
radius: parseFloat(data[i].val) / 2000,
value: parseFloat(data[i].val),
label: data[i].name
};
return data1;
}),
root = nodes[0],
color = d3.scale.category10();
root.radius = 0;
root.fixed = true;
//力导向
var force = d3.layout.force()
.gravity(0.01) //中心产生重力(通俗点说就是改变圆球之间的距离),数值越大挨得越近,0则没有重力
// .charge(function(d, i) { return i ? 0 : -2000; })
.nodes(nodes)
.size([width, height]);
force.start();
var padding = {left:-60, right:30, top:0, bottom:20};
var svg = d3.select("#countBall").append("svg")
.attr("width", width)
.attr("height", height);
//var ball = svg.selectAll("circle")
// .data(nodes.slice(1))
// .enter().append("circle")
// .attr("r", function(d) { return d.radius; })
// .style("fill", function(d, i) { return color(i % 3); })
// .append("text")
// .attr("class","text")
// .text(d => d.label)
// .attr("font-size", "30px")
// .attr("fill", "red")
// .attr("transform","translate(" + padding.left + "," + padding.top + ")");
var ball = svg.selectAll("g")
.data(nodes.slice(1));
var elemEnter = ball.enter()
.append("g")
.attr("transform","translate(" + padding.left + "," + padding.top + ")");
var circle = elemEnter.append("circle")
.attr("r", function(d) { return d.radius; })
.style("fill", function(d, i) { return color(i % 1); })
elemEnter.append("text")
.attr("class","text")
.text(d => d.label)
.attr("font-size", "16px")
.attr("fill", "#fff")
force.on("tick", function(e) {
var q = d3.geom.quadtree(nodes),
i = 0,
n = nodes.length;
//while (++i < n) q.visit(collide(nodes[i]));
svg.selectAll("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
svg.selectAll("text")
.attr("x", function(d) { return d.x - 16; })
.attr("y", function(d) { return d.y + 6; });
});
svg.on("mousemove", function() {
var p1 = d3.mouse(this);
root.px = p1[0];
root.py = p1[1];
force.resume();
});
function collide(node) {
var r = node.radius + 16,
nx1 = node.x - r,
nx2 = node.x + r,
ny1 = node.y - r,
ny2 = node.y + r;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
l = (l - r) / l * .5;
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
};
}
D3.js实现随机分布球形内含文字
最新推荐文章于 2023-04-07 09:36:45 发布