必须使用 d3 库将文本高度保存在 d 中

Have to save text height in d using d3 library

本文关键字:保存 高度 存在 文本 d3      更新时间:2023-09-26

我正在尝试将文本高度值保存在 d 中(这样我就可以在适当大小的矩形周围绘制),但它没有在 tick 函数或其他任何地方定义。

d.height

应该保存值。(但事实并非如此)

所以我有勾号功能(其中的一部分):

  function tick() {
    z.attr('d', function(d) {
    alert (d.height); //not defined
var sourceX = d.source.x + textWidth/2 + 10,
    sourceY = d.source.y + d.height/2 + 10,
    targetX = d.target.x + textWidth/2 + 10,
    targetY = d.target.y + d.height/2 + 10;      
return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
});
shape.attr('transform', function(d) {
middle_rect.attr("height", d.height/2 + 20);        
side_rect.attr("height", d.height/2 + 20);   
return 'translate(' + d.x + ',' + d.y + ')';        
});

这是我如何尝试保存值(代码底部)

     shape = shape.data(nodes);
// add new nodes
 var g = shape.enter().append('svg:g').attr('class', function(d) { return d.type +'        node'; });
   middle_rect = svg.selectAll(".middle")
   .append("svg:rect")
   .attr("rx", "10")
   .attr("ry", "10")
   .style("stroke", "rgb(47,136,214)")
   .style("fill", "url(#middle_gradient)");

  side_rect = svg.selectAll(".side")
   .append("svg:rect")
   .attr("rx", "10")
   .attr("ry", "10")
   .style("stroke", "rgb(47,136,214)")
   .style("fill", "url(#side_gradient)");

  txt = g.append('svg:text')
   .attr('class',function (d){return 'bigest ' + d.id ;}  )
   .attr('y', ".5em")
   .attr("dy", "1em")
   .style("fill", "black")
   .each (function (d) {
    d.height =  this.getBoundingClientRect().height;
    // alert (d.height); //here I have this value
});

我可以将其全球化吗?还是必须保存这些值?

您似乎正在尝试将高度字段附加到节点本身,这通常被认为是一种不好的做法。

为什么不创建一个数据结构来存储所有这些值,甚至可能将高度添加到数据集中。

另一种方法是在文本节点上创建数据高度属性。

http://jsfiddle.net/heavyhorse/893jT/

svg.selectAll('text.data-label').each(function(d, i){
    var height = this.getBoundingClientRect().height;
    var width = this.getBoundingClientRect().width;
    console.log(i+': ('+width+','+height+')');
    // create custom data-attr:
    this.setAttribute('data-width', width);
    this.setAttribute('data-height', height);
    console.log(this);
    // attach to dataset:
    dataset[i].width = width;
    dataset[i].height = height;
});