Reputation: 12487
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.
Upvotes: 0
Views: 131
Reputation: 3488
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>
Upvotes: 1