我看过D3.js的例子- Voronoi Tessellation。但是我想在每个多边形中放置一些文本,而不是一个圆圈。这里是我的js代码:
var width = 600, height = 400;
var vertices = d3.range(20).map(function(d){
return [Math.random() * width, Math.random() * height]
});
var voronoi = d3.geom.voronoi();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
path = svg.append("g").selectAll("path");
svg.selectAll("info")
.data(vertices.slice(1))
.enter().append("text")
.attr("transform", function(d) {
return "translate(" + d + ")";
})
.text("someText")
.attr("shape-rendering","crispEdges")
.style("text-anchor","middle");
redraw();
function redraw(){
path = path
.data(voronoi(vertices), polygon);
path.exit().remove();
path.enter().append("path")
.attr("class", function(d, i) {return "q" + (i % 9) + "-9";})
.attr("d", polygon);
path.order();
}
function polygon(d){
return "M" + d.join("L") + "Z";
}
我有一个基本示例的JSFiddle: 我的voronoi代码 现在,我希望每个多边形的文本都位于多边形的中心,并且不要与多边形的边框重叠。如果多边形没有足够的空间来容纳所有文本,只需包含其第一部分即可! 请让我知道是否有什么可以解决这个问题,谢谢!
PS:非常抱歉我的英语很差! :)