5

Im using svgjs to create my shapes. How can I find the center point of an svg shape and add an element there? In my case a red dot. I can't find any information in the documentation for a method or something that helps in this situation.

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
Pedro
  • 1,459
  • 6
  • 22
  • 40

1 Answers1

9

You can use the method getBBox or alternatively getBoundingClientRect. Both methods give you an object with the properties x, y, width, height, which you can use to calculate your center.

Since you tagged your question with svg.js I will also give you a solution with svg.js.

// Vanilla
node = document.getElementById('myEl').getBBox()

// with svg.js
SVG.adopt(document.getElementById('myEl')).bbox()

The second solution gives you back an object which has cx and cy already calculated for you.

This method can be found in the docs

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
  • Thanks a lot for the answer, one last question, after getting the coordinates how would i set a element on this positions? – Pedro Oct 26 '16 at 22:25
  • I would use the `center` function to set the center of the element to the center of the shaoe. E.g. `circleEl.center(cx, cy)`. Thats all written in the docs. Please rtfm! – Fuzzyma Oct 27 '16 at 07:23
  • Thanks a lot, for the help, but i notice one issue, when i call SVG.adopt(this.svgElement).bbox() i notice that is giving me only 2 coordinates, and after i console.log(this.svgElement), i notice that there are 2 svg, where in each of theme, inside are 2 shapes, rect and circle, but i need to position a element in the center of the shapes inside the svg, how i would do that? – Pedro Oct 27 '16 at 09:39