如何为d3文本元素添加背景色?

皮埃尔

我正在尝试在带有d3的文本后面添加一个rect元素,以模拟d3文本元素不存在的背景色。我希望rect具有与文本本身完全相同的大小。

node.append("text") 
    .attr("class", "text")
    .attr("text-anchor", "middle")
    .attr("dx", 0)
    .attr("dy", ".35em")
    .text(function(d) {
          var bbox = this.getBBox();
          node.insert("rect",":first-child")
          .attr("x", bbox.x)
          .attr("y", bbox.y)
          .attr("width", bbox.width)
          .attr("height", bbox.height)
          .style("fill", "yellow");
        return d.name;
    });

this.getBBox()对于x和y均返回0。

以下代码显示了该框,但是它的大小与文本大小并不一致,即使没有文本(存在图像时),该框也会被绘制。

node.filter(function(d) {return (!d.image)}).append("text") 
    .attr("class", function(d) { return "text "+d.type; })
    .attr("text-anchor", "middle")
    .attr("dx", 0)
    .attr("dy", ".35em")
    //.text(function(d) { if (!d.imgB64) { return d.label; }
    .text(function(d) {
        return d.name;
    })
    .each(function(d) {
       var bbox = this.getBBox();
          node.insert("rect", "text")
          .style("fill", "#FFE6F0")
          .attr("x", bbox.x)
          .attr("y", bbox.y)
          .attr("width", bbox.width)
          .attr("height", bbox.height);
    });

多亏了Cool Blue,下面的代码现在可以正常工作:在文本后面显示一个rect,以便在大于节点圆时可读。在未来,可以用球面弧而不是矩形来改进,只将圆形框架隐藏在文本后面。

在此处输入图片说明

// only display node labels if node has no image 
node.filter(function(d) {return (!d.image)}).append("text") 
    .attr("class", function(d) { return "text "+d.type; })
    .attr("text-anchor", "middle")
    .attr("dx", 0)
    .attr("dy", ".35em")
    .text(function(d) {
        return d.name;
    })
    .call(getTextBox);

// only display a rect behind labels if node has no image 
node.filter(function(d) {return (!d.image)}).insert("rect","text")
    .attr("x", function(d){return d.bbox.x})
    .attr("y", function(d){return d.bbox.y})
    .attr("width", function(d){return d.bbox.width})
    .attr("height", function(d){return d.bbox.height})
    .style("fill", "#FFE6F0");

function getTextBox(selection) {
    selection.each(function(d) { d.bbox = this.getBBox(); })
}
酷蓝

如评论中所述,使用此模式并添加所需的任何详细信息...

var textNode = node.filter(function(d) {return (!d.image)})

textNode.append("text") 
    .attr("class", "text")
    .attr("text-anchor", "middle")
    .attr("dx", 0)
    .attr("dy", ".35em")
    .text(function(d) {
        return d.name;
    }).call(getBB);   
textNode.insert("rect","text")
    .attr("width", function(d){return d.bbox.width})
    .attr("height", function(d){return d.bbox.height})
    .style("fill", "yellow");

function getBB(selection) {
    selection.each(function(d){d.bbox = this.getBBox();})
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章