Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preemptive getBBox calculation

When there is an SVG element that is in the DOM, it's possible to get its bounding box using the getBBox function, as illustrated in this example:

http://bl.ocks.org/mbostock/1160929

Is it possible to get the bounding box without actually adding an element to the DOM?

In other words, can I calculate what the bounding box of some text would be if it was attached to certain node without actually attaching it?

The goal is to iteratively add labels to a graphic while avoiding overlapping text.

like image 741
juniper- Avatar asked Jan 31 '16 20:01

juniper-


2 Answers

There is no way to calculate the height of a text before displaying it. The reason is that their might me many things that influence the height of the text (css classes, font present or not in the computer ...).

The easiest way to achieve it is to create the text hidden, get its height and then calculate the position.

like image 50
Mijamo Avatar answered Nov 17 '22 08:11

Mijamo


How about

  1. Adding the text
  2. Get Bounds
  3. Removing the text.

Something like this:

//add the text
var text = svg.append("text")
    .attr("id", "text-to-remove")
    .attr("x", 480)
    .attr("y", 250)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .style("font", "300 128px Helvetica Neue")
    .text("Hello, getBBox!");
//get bbox
var bbox = text.node().getBBox();

//remove the text

d3.select("#text-to-remove").remove();

//use bbox
var rect = svg.append("rect")
    .attr("x", bbox.x)
    .attr("y", bbox.y)
    .attr("width", bbox.width)
    .attr("height", bbox.height)
    .style("fill", "#ccc")
    .style("fill-opacity", ".3")
    .style("stroke", "#666")
    .style("stroke-width", "1.5px");

working code here

Hope this helps!

like image 40
Cyril Cherian Avatar answered Nov 17 '22 07:11

Cyril Cherian