textPath answer

by mklemma

HTML

<svg width="600" height="400" xmlns="http://www.w3.org/2000/svg" style="font-family: Times New Roman;font-size: 14px;">
        <path d="M 30 160 Q 150 0 300 160" stroke="black" fill="none" id="path1"></path>
        <text id="text1">
        <textPath href="#path1" id="textPath1">This is a pen.</textPath>
        </text>
</svg>

JavaScript

const textLength = 300;
const svgText = document.getElementById('text1');
const svgTextPath = document.getElementById('textPath1');

//letter-spacing=0のときのテキストの幅
const box = svgText.getBBox();
//元々のテキストの幅とtextLengthのギャップ
const diff = textLength - box.width;
//テキストの長さ
const number = svgTextPath.textContent.length;
//文字間の隙間の数はテキスト長-1だからギャップ/テキスト長-1で割れば大丈夫だろう…
const w = diff / (number - 1);

//Edge用属性
svgText.setAttribute("letter-spacing", `${w}`);
//Firefox用属性
svgText.setAttribute("textLength", `${textLength}`);
//Chrome用属性
svgTextPath.setAttribute("textLength", `${textLength}`);