Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active March 19, 2018 02:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mbostock/1160929 to your computer and use it in GitHub Desktop.
Save mbostock/1160929 to your computer and use it in GitHub Desktop.
getBBox
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var text = svg.append("text")
.attr("x", 480)
.attr("y", 250)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("font", "300 128px Helvetica Neue")
.text("Hello, getBBox!");
var bbox = text.node().getBBox();
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");
</script>
@keithpjolley
Copy link

if you are needing to draw the text after the rect, like if the fill-opacity is 1.0, you can do this:

var svg = d3.select("body").append("svg:svg")
    .attr(...)

var layer1 = svg.append('g')  // draw in this order
var layer2 = svg.append('g')

var text = layer2.append("svg:text")      // create in this order
    .attr(.....)

var bbox = text.node().getBBox();

var rect = layer1.append("svg:rect")
    .attr(...)
    .attr("width", bbox.width)
    .attr("height", bbox.height)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment