英文:
HTML in SVG textPath?
问题
在我的React应用程序中,我试图获取包含HTML span(如下所示:“Made with ❤️ since 2023”)的文本,以便在SVG文本路径中显示(该文本路径本身遵循一个圆形路径)。
我已尝试使用foreignObject包装此HTML,如下所示:
<svg className="svg" viewBox="0 0 100 100">
<path
id="circle"
d="M 50,50 m -40,0 a 40,40 0 1,0 80,0 a 40,40 0 1,0 -80,0"
fill="transparent"
/>
<text width="100px" height="100px">
<textPath id="text" className="textPath" href="#circle">
<foreignObject
x="0"
y="0"
width="100"
height="100"
id="text"
className="textPath"
href="#circle"
xmlns="http://www.w3.org/1999/xhtml"
dangerouslySetInnerHTML={{
__html: `<p>Made with <span role="img" aria-label="love">❤️</span> since 2023</p>`,
}}
/>
</textPath>
</text>
</svg>
尽管我可以看到HTML字符串在DOM中正常呈现,但它似乎无法显示,因为<text>
和<textPath>
似乎都没有宽度或高度。我是否遗漏了什么,或者根本无法在textPath
中使用foreignObject
?非常感谢任何其他解决方案!
英文:
In my React app, I'm trying to get some text, containing html spans (like so: "Made with <span role="img" aria-label="love">❤️</span> since 2023" to display in an SVG text path (which itself follows a circle path).
I have tried wrapping this html using foreignObject, like so:
<svg className="svg" viewBox="0 0 100 100">
<path
id="circle"
d="M 50,50 m -40,0 a 40,40 0 1,0 80,0 a 40,40 0 1,0 -80,0"
fill="transparent"
/>
<text width="100px" height="100px">
<textPath id="text" className="textPath" href="#circle">
<foreignObject
x="0"
y="0"
width="100"
height="100"
id="text"
className="textPath"
href="#circle"
xmlns="http://www.w3.org/1999/xhtml"
dangerouslySetInnerHTML={{
__html: `<p>Made with <span role="img" aria-label="love">❤️</span> since 2023</p>`,
}}
/>
</textPath>
</text>
</svg>
and, although I can see the html string is rendered just fine in the DOM. It is nowhere to be seen, as it seems that both <text>
and <textPath>
have no width or height. Am I missing something or is it simply not possible to use foreignObject
in a textPath
? Any other solutions much appreciated!
答案1
得分: 1
为在SVG路径中显示文本,您可以使用SVG tspan
元素而不是 foreignObject
。类似于这样的内容:
<svg className="svg" viewBox="0 0 100 100">
<path
id="circle"
d="M 50,50 m -40,0 a 40,40 0 1,0 80,0 a 40,40 0 1,0 -80,0"
fill="transparent"
/>
<text>
<textPath id="text" className="textPath" href="#circle">
<tspan x="0" dy="1em">Made with</tspan>
<tspan x="0" dy="1em">❤️ since 2023</tspan>
</textPath>
</text>
</svg>
用于微调的 tspan
属性在此处有描述。
英文:
To display text in an SVG path, you can use the SVG tspan
element instead of foreignObject
. Smth like this:
<svg className="svg" viewBox="0 0 100 100">
<path
id="circle"
d="M 50,50 m -40,0 a 40,40 0 1,0 80,0 a 40,40 0 1,0 -80,0"
fill="transparent"
/>
<text>
<textPath id="text" className="textPath" href="#circle">
<tspan x="0" dy="1em">Made with</tspan>
<tspan x="0" dy="1em">❤️ since 2023</tspan>
</textPath>
</text>
</svg>
Attributes of tspan
for fine-tuning are described here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论