0
votes

It is hard to know what dimensions text requires, especially if it's rotated. As a result, it is easy to make the viewBox too small and then the text disappears outside the viewBox. However, if the viewBox is too big, then there is a ton of extra whitespace that also gets scaled. Is there a way to scale the viewBox or the svg contents to fit?

I know about preserveAspectRatio to scale a viewBox to the width and height of the svg, but I'm asking about scaling to fit the viewBox.

More generally, how do I approach determining the viewBox dimensions for text?

1
You mean dynamically? Can it be done by scripts? Are you just looking for a general way of doing it manually? Or are you looking for some markup that would allow to do it automatically?Kaiido

1 Answers

1
votes

The easy javascript way is to get the BBox of your container and to apply it as its viewBox attribute.

onclick = e => {
  const svg = document.querySelector('svg');
  const bbox = svg.getBBox();
  svg.setAttribute('viewBox', `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);
  console.log(bbox);

};
svg {
  border: 1px solid;
}
text {
  font: 16px "Times Roman";
}
<svg width="300" height="150">
  <text x="0" y="50" >Click to adjust</text>
</svg>

You can obviously also call it manually from your browser and then copy it manually to your markup:

svg {
  border: 1px solid;
}
text {
  font: 16px "Times Roman";
}
<svg width="300" height="150" viewBox="0 36 93.34375 18">
  <text x="0" y="50">Click to adjust</text>
</svg>

However, there is nothing in my knowledge that will allow you to set up a viewBox that would be aware of its content. That is, you can not do something like viewBox="contain".