Skip to content

Instantly share code, notes, and snippets.

@nitaku
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitaku/8745544 to your computer and use it in GitHub Desktop.
Save nitaku/8745544 to your computer and use it in GitHub Desktop.
SVG text bounding box

An example that uses the SVG DOM function getBBox() to highlight a text element.

width = 960
height = 500
### create the SVG ###
svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
# create a text element
text = svg.append('text')
.text('Hello world!')
.attr('x', 480)
.attr('y', 250)
.attr('dy','0.35em')
# obtain its bounding box (without considering transforms)
bbox = text[0][0].getBBox()
# insert a yellow rect beneath the text, to represent the bounding box
svg.insert('rect','text')
.attr('x', bbox.x)
.attr('y', bbox.y)
.attr('width', bbox.width)
.attr('height', bbox.height)
text {
font-size: 80px;
font-family: Georgia;
text-anchor: middle;
}
rect {
fill: yellow;
opacity: 0.3;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SVG text bounding box</title>
<link type="text/css" href="index.css" rel="stylesheet"/>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
</body>
<script src="index.js"></script>
</html>
(function() {
var bbox, height, svg, text, width;
width = 960;
height = 500;
/* create the SVG
*/
svg = d3.select('body').append('svg').attr('width', width).attr('height', height);
text = svg.append('text').text('Hello world!').attr('x', 480).attr('y', 250).attr('dy', '0.35em');
bbox = text[0][0].getBBox();
svg.insert('rect', 'text').attr('x', bbox.x).attr('y', bbox.y).attr('width', bbox.width).attr('height', bbox.height);
}).call(this);
text
font-size: 80px
font-family: Georgia
text-anchor: middle
rect
fill: yellow
opacity: 0.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment