纯SVG方式使文本适合框 [英] Pure SVG way to fit text to a box

查看:63
本文介绍了纯SVG方式使文本适合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已知盒子大小.文字字串长度未知.使文本适合框,而不会破坏其长宽比.

Box size known. Text string length unknown. Fit text to box without ruining its aspect ratio.

经过一个晚上的搜索并阅读了SVG规范之后,我很确定如果没有JavaScript,这是不可能的.我能得到的最接近的是使用textLength和lengthAdjust文本属性,但这仅沿一个轴拉伸文本.

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>

我知道 SVG缩放文本以适合容器将文本放入框中

推荐答案

在没有Java脚本的情况下,我找不到直接解决问题的方法,但是我找到了一个非常简单的JS解决方案,没有for循环,也没有修改字体大小并适合所有尺寸,也就是说,文本会一直增长到最短边的限制.

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.

基本上,我使用transform属性,计算所需大小与当前大小之间的正确比例.

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

这是代码:

<?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>

在前面的示例中,文本增长到width == 500,但是如果我使用width = 500height = 30的框大小,则文本增长到height == 30.

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.

这篇关于纯SVG方式使文本适合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆