Сначала мне нужно вычислить ширину текста (txtlength
) и ширину поля (w
).Я хочу масштабировать текст, поэтому я вычисляю масштаб let thescale = w / (2*txtlength);
.// это масштабирует текст на 50% ширины прямоугольника.Затем, используя setAttributeNS, я устанавливаю значение для атрибута transform.Обратите внимание, что в тексте нет атрибутов x и y, центрированных вокруг источника SVG-холста.
let txtlength = txt.getComputedTextLength()
let w = theRect.getBBox().width;
let c = {x:50,y:25}// the center of the rect
let thescale = w / (2 * txtlength);// 50% of rect's width
//scale the text and translate in the center
txt.setAttributeNS(null, "transform", `scale(${thescale},${thescale}) translate(${c.x/thescale},${c.y/thescale})`)
svg{border:1px solid; width:120vh}
text{font-size:10;
dominant-baseline: middle;
text-anchor: middle}
<svg viewBox="0 0 100 50">
<rect id="theRect" x="10" y="10" width="80" height ="30" stroke="black" fill="none" />
<text id="txt" dominant-baseline="middle" text-anchor="middle">A very long text, sooo long </text>
</svg>