我已經看到D3.js- Voronoi Tessellation的例子。但我希望把一些文字中的每個多邊形,而不是圓的,這是我的js代碼:如何用D3.js限制Voronoi圖中的多邊形文本?
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爲這裏的基本示例: my voronoi code
現在,我希望每個多邊形的文本位於多邊形的中心,並且不要與多邊形的邊框交叉。如果多邊形沒有足夠的空間來容納全部文本,只需包含它的第一部分! 讓我知道如果有什麼我可以做的解決這個問題,謝謝! PS:我很抱歉我的英語,是的,它太可憐了! :)
件文成多邊形是不平凡的。首先,您需要找出文本的最佳位置(因爲某些多邊形非常不規則),然後確定文本的大小,多邊形的大小以及它們相交的位置。然後根據這個縮短文本。剪輯路徑可能會更容易。 –
@LarsKotthoff你能告訴我一些關於剪輯路徑的文章嗎? :) – CodingMonkey
看看例如[這裏](http://www.svgbasics.com/clipping.html)。 –