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

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

问题描述

盒子尺寸已知.文本字符串长度未知.使文本适合框而不破坏其纵横比.

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

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

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 缩放文本以适应容器将文本放入框中

推荐答案

我没有找到不用 Javascript 直接完成的方法,但我找到了一个 JS 非常简单的解决方案,无需 for 循环,无需修改 font-size并且适合所有维度,即文本增长到最短边的极限.

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天全站免登陆