Pure SVG way to fit text to a box

svg

Solution

I didn't find a way to do it directly without Javascript, but I found a JS quite easy solution, without for loops and without modify the font-size and fits well in all dimensions, that is, the text grows until the limit of the shortest side.

Basically, I use the `transform` property, calculating the right proportion between the desired size and the current one.

This is the code:

<?xml version="1.0" encoding="UTF-8" ?>
<svg version="1.2" viewBox="0 0 1000 1000" width="1000" height="1000" xmlns="http://www.w3.org/2000/svg" >
 <text id="t1" y="50" >MY UGLY TEXT</text>
 <script type="application/ecmascript"> 

    var width=500, height=500;

    var textNode = document.getElementById("t1");
    var bb = textNode.getBBox();
    var widthTransform = width / bb.width;
    var heightTransform = height / bb.height;
    var value = widthTransform < heightTransform ? widthTransform : heightTransform;
    textNode.setAttribute("transform", "matrix("+value+", 0, 0, "+value+", 0,0)");

 </script>
</svg>

In the previous example the text grows until the `width == 500`, but if I use a box size of `width = 500` and `height = 30`, then the text grows until `height == 30`.

Problem

Box size known. Text string length unknown. Fit text to box without ruining its aspect ratio. After an evening of googling and reading the SVG spec, I'm pretty sure this isn't possible without JavaScript. The closest I could get was using the `textLength` and `lengthAdjust` text attributes, but that stretches the text along one axis only. ``` <svg width="436" height="180" style="border:solid 6px" xmlns="http://www.w3.org/2000/svg"> <text y="50%" textLength="436" lengthAdjust="spacingAndGlyphs">UGLY TEXT</text> </svg> ``` I am aware of SVG Scaling Text to fit container and fitting text into the box

Original source

Related problems