0

I've been playing around with the code here: https://stackoverflow.com/a/22580176/1738522

It uses javascript to determine the font size in order to fit within a max of 350px width or max of 80px height. This is the code

<div style="background: grey; display: inline-block;">
<svg version="1.2" viewBox="0 0 600 400" width="600" height="400" xmlns="http://www.w3.org/2000/svg" >
 <text id="t1" y="50" style="fill: white;">MfgfgfgghgY UGLY TEXT</text>
 <script type="application/ecmascript"> 
    var width=350, height=80;
    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>
</div>

https://jsfiddle.net/spadez/4Lb3sg0m/8/embedded/result/

This works perfectly, except for it doesn't position the text within the centre of the viewport. Normally since we know text size and viewport it would be easy, however since the text size is limited by width OR height, we don't know the exact final figures.

TL;RD How to change this javascript/SVG to dynamically position the text in the vertical and horizontal centre of the view port.

Community
  • 1
  • 1
Jimmy
  • 12,087
  • 28
  • 102
  • 192

1 Answers1

1

If you want to set font-size and center the text at the middle of the SVG, then try the following:

<!DOCTYPE HTML>
<html>

<body>
 <div style="background: grey; display: inline-block;">
<svg version="1.2" viewBox="0 0 600 400" width="600" height="400" xmlns="http://www.w3.org/2000/svg" >
 <text id="t1"  text-anchor="middle" x="50%" y="50%" style="fill: white;">MfgfgfgghgY UGLY TEXT</text>
</svg>
 <script>
    var width=350, height=80;
    var textNode = document.getElementById("t1");
    for(var k=1;k<60;k++)
    {
        textNode.setAttribute("font-size",k)
        var bb=textNode.getBBox()
        if(bb.width>width||bb.height>height)
            break;
    }
 </script>

</div>
</body>

</html>
Francis Hemsher
  • 3,478
  • 2
  • 13
  • 15
  • Hi! Thank you for the reply. I notice the JS is a bit different to the question, is there any reason for that? So far as I can see the main difference is the ```text-anchor="middle" x="50%" y="50%"``` but when I add it to my code it doesn't work for some reason https://jsfiddle.net/spadez/8uvw1xn6/3/ – Jimmy Mar 02 '17 at 20:56
  • Replace with the JS as shown in the example, removing transform. – Francis Hemsher Mar 02 '17 at 21:00
  • But the trouble is your JS (not sure why) falls over when trying to use custom fonts, whereas the original JS works ok with google fonts and keeps the width to 350px wide (example: https://jsfiddle.net/spadez/3pydzeu4/) – Jimmy Mar 02 '17 at 21:22
  • I'll mark it as answered because it is a help and I'm sure it's just a minor niggle stopping it working – Jimmy Mar 02 '17 at 21:39