[英]How can I draw text on a D3 SVG iff it's bounding box falls within certain criteria?
我正在使用D3.js在SVG容器上繪制一些文本。 在繪制文本時,我會稍微翻譯其位置。 我將翻譯后的文本的左邊界的x位置存儲在稱為a
的變量中
var a = null;
var label = svgContainer.append("text")
.attr("x", 200)
.attr("y", 300)
.text("Hello World")
.attr("font-family", "Courier New")
.attr("font-weight", "bold")
.attr("font-size", "10px")
.attr("fill", "black")
.attr("transform", function(d){
var bb = this.getBBox();
console.log("bb.x = ", bb.x);
console.log("bb.y = ", bb.y);
console.log("bb.width = ", bb.width);
console.log("bb.height = ", bb.height);
a = bb.x - (bb.width/2);
return "translate(" + (bb.width / (-2)) + ", 0)";
}
);
我想更改此代碼,以便當且僅當 a < 100
時才繪制文本。 我該怎么做? 問題在於,僅在繪制文本時計算a並為其分配值。 到那個時候為時已晚。 在實際繪制文本之前如何獲取值?
您可以在獲取BBox之后添加: .style("display", "none")
:
var a = null;
var label = svgContainer.append("text")
.attr("x", 100)
.attr("y", 10)
.text("Hello World")
.attr("font-family", "Courier New")
.attr("font-weight", "bold")
.attr("font-size", "10px")
.attr("fill", "black")
.attr("transform", function(d){
var bb = this.getBBox();
console.log("bb.x = ", bb.x);
console.log("bb.y = ", bb.y);
console.log("bb.width = ", bb.width);
console.log("bb.height = ", bb.height);
a = bb.x - (bb.width/2);
return "translate(" + (bb.width / (-2)) + ", 0)";
}
)
.style("display", "none");
然后使用: svgContainer.selectAll("text")
svgContainer.selectAll("text")
.attr("x", function(d) {
// enter your code/ validations in here
})
.style("display", "block");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.