Skip to content

Instantly share code, notes, and snippets.

@nitaku
Last active July 9, 2021 02:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitaku/d75ea826aed291c3ee00 to your computer and use it in GitHub Desktop.
Save nitaku/d75ea826aed291c3ee00 to your computer and use it in GitHub Desktop.
Fit text to box

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.

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}"
svg {
background: white;
}
rect {
stroke-width: 4;
stroke-opacity: 0.3;
stroke: #333;
fill: none;
}
text {
fill: black;
font-size: 64px;
text-anchor: middle;
}
<!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="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<svg height="500" width="960"></svg>
<script src="index.js"></script>
</body>
</html>
(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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment