block by nitaku 8745544

SVG text bounding box

Full Screen

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

index.js

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

index.html

<!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="//d3js.org/d3.v3.min.js"></script>
    </head>
    <body>
    </body>
    <script src="index.js"></script>
</html>

index.coffee

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)
  

index.css

text {
  font-size: 80px;
  font-family: Georgia;
  text-anchor: middle;
}

rect {
  fill: yellow;
  opacity: 0.3;
}

index.sass

text
    font-size: 80px
    font-family: Georgia
    text-anchor: middle
    
rect
    fill: yellow
    opacity: 0.3