Skip to content
Advertisement

Add text to SVG path dynamically

I have an SVG exported from Adobe Illustrator with several paths like this, which produces a small polygon I intend to use as a text box

JavaScript

I’d like to dynamically add text to it. I’ve seen many similar questions here, but most of them involed specifying a x and y property for a text element based on the x and y property the path element. My path, however, does not have such properties.

I’ve tried to use a textPath element with xlink:href pointing to my path. I gets attached to the path, but the text wraps my path element instead of being inside it.

So, is there a way to achieve this? I’m open to different solutions here. My dream would be to use javascript to get the path element and add the text from there. But I could also edit the base SVG file to add a text or any other relevant element and attributes to make this work, as long as I can change the text dynamically from javascript later. And since this SVG is produced by Illustrator, I could also try different export options there in order to get a proper output for my goal.

Advertisement

Answer

Here’s some sample code that takes a label path and adds a <text> element after it with whatever text you choose.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement