如何在D3 SVG上绘制文本,如果它's的边界框符合某些标准

How can I draw text on a D3 SVG iff it's bounding box falls within certain criteria?

本文关键字:边界 标准 SVG D3 绘制 如果 文本      更新时间:2023-09-26

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