Search code examples
javascriptd3.jsgetboundingclientrect

Have to save text height in d using d3 library


I am trying to save text height value in d (so I can draw around appropriate size rectangle), but it's not defined in tick function or any where else.

d.height

should hold values. (but it doesn't)

So I have tick function (part of it):

  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 + ')';        
});

And here how I'm trying to save values (bottom of code)

     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
});

Can I make it global? Or have to save these values?


Solution

  • It appears that you are trying to attach a height field to the Node itself, which is considered a bad practice in general.

    Why not create a data structure to store all these values, or possibly even add the height to your dataset.

    Another approach could be creating a data-height attribute on the text node.

    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;
    });