我觉得我有一个非常愚蠢的问题:我使用以下命令创建一个文本:
text = document.createElementNS("http://www.w3.org/2000/svg", "text")
text.textContent = "some very long text"
如何使打印的字符串跨多行?常见的
'\n'
不起作用。我使用 <br/>
命令找到了一些 html 文本的解决方案,但我不知道将文本转换为 html。我也试过了
text.innerHTML = "some text" + <br/> + "some more text"
但这没有用。
SVG 文本元素不直接支持换行符或 HTML 标签。相反,您必须手动将文本分成单独的元素。每个都可以单独定位以模拟换行符。这是一个例子:
const svg = document.querySelector("svg");
const text = document.createElementNS("http://www.w3.org/2000/svg",
"text");
text.setAttribute("x", "10");
text.setAttribute("y", "20");
text.setAttribute("font-size", "16");
const lines = ["some very long text", "that spans over", "multiple lines"];
lines.forEach((line, index) => {
const tspan = document.createElementNS("http://www.w3.org/2000/svg",
"tspan");
tspan.setAttribute("x", "10");
tspan.setAttribute("dy", "1.2em");
tspan.textContent = line;
text.appendChild(tspan);
});
svg.appendChild(text);