gpt4 book ai didi

javascript - 如果 D3 SVG 的边界框符合特定标准,如何在 D3 SVG 上绘制文本?

转载 作者:行者123 更新时间:2023-12-03 07:20:42 27 4
gpt4 key购买 nike

我正在使用 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");

关于javascript - 如果 D3 SVG 的边界框符合特定标准,如何在 D3 SVG 上绘制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36232275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com