Get width of d3.js SVG text element after it's created

后端 未结 3 1613
梦毁少年i
梦毁少年i 2021-02-19 00:43

I\'m trying to get the widths of a bunch of text elements I have created with d3.js

This is how I\'m creating them:

var nodesText = svg.sel         


        
3条回答
  •  青春惊慌失措
    2021-02-19 01:06

    I would make the length part of the original data:

    var nodesText = svg.selectAll("text")
           .data(dataset)
           .enter()
           .append("text")
           .text(function(d) {
                return d.name;
           })
          .attr("x", function(d, i) {
                return i * (w / dataset.length);
           })
          .attr("y", function(d) {
                return 45;
          })
          .each(function(d) {
            d.width = this.getBBox().width;
          });
    

    and then later

    var nodes = svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("width", function(d) { return d.width; });
    

提交回复
热议问题