tjp
tjp

Reputation: 161

Is there a simple way to draw centred text over an existing SVG path in the DOM using Javascript?

I'm using a charting library which places an SVG image on the page. I can get the Path element in Javascript.

I need to be able to draw text centred over the area defined by the path.

There is the Raphael.js library which simplifies drawing text in SVG, but I can't figure out how to use it to edit an existing SVG in HTML after the page loads. How can I do this? I don't mind if I have to use Raphael.js or some other dependency.

Upvotes: 2

Views: 433

Answers (2)

ccprog
ccprog

Reputation: 21821

Get the size and position of the path in its local coordinate system:

var myPath = svgDocument.querySelector('#myPath');
var boundingBox = myPath.getBBox();

Append the text to the same parent element as the path, positioned in the middle:

var text = svgDocument.createElementNS('http://www.w3.org/2000/svg', 'text');
text.style['text-anchor'] = 'middle';
text.style['dominant-baseline'] = 'middle';
text.setAttribute('x', boundingBox.x + boundingBox.width/2);
text.setAttribute('y', boundingBox.y + boundingBox.height/2);
myPath.parentElement.appendChild(text);

It is important to notice that you won't get information about transforms happening on any parent elements, so you need to ensure that you are working in relation to the same coordinate system.

Upvotes: 2

jasonleehodges
jasonleehodges

Reputation: 311

Can you group the path and the text object together to get relative positioning? You can assign the following attributes to the text object to help with centering:

  • text-anchor="middle"
  • x="50%"
  • y ="50%"

Upvotes: 0

Related Questions