block by nitaku d75ea826aed291c3ee00

Fit text to box

Full Screen

This example shows a way to stretch some text to fit a given rectangular area, using SVG’s viewPort attribute. The computed bounding box of the text is larger than the minimum rectangle that contains its actual representation, causing some space to be left at the top, right and bottom.

index.js

(function() {
  var bbox, height, inner_svg, svg, txt, width;

  svg = d3.select('svg');

  width = svg.node().getBoundingClientRect().width;

  height = svg.node().getBoundingClientRect().height;

  svg.attr({
    viewBox: "" + (-width / 2) + " " + (-height / 2) + " " + width + " " + height
  });

  svg.append('rect').attr({
    x: -380,
    y: -200,
    width: 760,
    height: 400
  });

  inner_svg = svg.append('svg').attr({
    x: -380,
    y: -200,
    width: 760,
    height: 400,
    preserveAspectRatio: 'none'
  });

  txt = inner_svg.append('text').text('Hello Ground!');

  bbox = txt.node().getBBox();

  inner_svg.attr({
    viewBox: "" + bbox.x + " " + bbox.y + " " + bbox.width + " " + bbox.height
  });

}).call(this);

index.html

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8">
        <meta name="description" content="Fit text to box" />
        <title>Fit text to box</title>
		<link type="text/css" href="index.css" rel="stylesheet"/>
        <script src="//d3js.org/d3.v3.min.js"></script>
	</head>
	<body>
        <svg height="500" width="960"></svg>
        <script src="index.js"></script>
	</body>
</html>

index.coffee

svg = d3.select('svg')
width = svg.node().getBoundingClientRect().width
height = svg.node().getBoundingClientRect().height

# translate the viewBox to have (0,0) at the center of the vis
svg
  .attr
    viewBox: "#{-width/2} #{-height/2} #{width} #{height}"
    
svg.append('rect')
  .attr
    x: -380
    y: -200
    width: 760
    height: 400
    
inner_svg = svg.append('svg')
  .attr
    x: -380
    y: -200
    width: 760
    height: 400
    preserveAspectRatio: 'none'

txt = inner_svg.append('text')
  .text('Hello Ground!')
  
bbox = txt.node().getBBox()

inner_svg
  .attr
    viewBox: "#{bbox.x} #{bbox.y} #{bbox.width} #{bbox.height}"

index.css

svg {
  background: white;
}
rect {
  stroke-width: 4;
  stroke-opacity: 0.3;
  stroke: #333;
  fill: none;
}
text {
  fill: black;
  font-size: 64px;
  text-anchor: middle;
}