How to get the position of an <Circle> element that is inside an SVG via Javascript?

Asked

Viewed 309 times

5

I have an SVG that contains, among other items, an element <circle>. I can manipulate it via Javascript by changing CSS properties such as visibility, but I can’t get his position on the screen.

My idea is that when the mouse passes over certain <div>, another <div> is displayed based on the position of the <circle>.

I tried to use the offsetTop, but it didn’t work.

1 answer

3


The Circle position is defined by the attributes cx and cy.

<svg>
    <circle cx="50" cy="50" r="15"></circle>
</svg>
var circulo = document.querySelector('circle');
circulo.addEventListener('mouseover', function() {
    console.log(this.getAttribute('cx'), this.getAttribute('cy'));
});

http://jsfiddle.net/6L59khr6/

This position relates to that of the SVG element.

  • Thus, to know the distance of < Circle > to the top of the screen I would have to take the coordinate "Cy" and then add with the coordinate of < svg > ?

  • Exactly, Dionei.

  • 2

    Referring to Dionei’s question, in the comments, not exactly, because it depends on the proportion and scale of the SVG.

  • Well, anyway it’s already a way... I’ll work on it to solve my problem. Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.