At the event mousemove
of a given element, you get the cursor coordinates in relation to the window with the properties clientX
and clientY
of the event:
elemento.onmousemove = function(e) {
// coordenadas em e.clientX e e.clientY
}
To calculate the coordinate relative to the element itself, or to some other element, you first need to figure out the position of the element in the window. This you get with the getBoundingClientRect()
of the element:
var boxDoElemento = elemento.getBoundingClientRect();
alert(boxDoElemento.left); // posição x
alert(boxDoElemento.top); // posição y
If there is no page rolling, simply subtract the element position from the mouse cursor position to get the relative position. If there is rolling, you need to discount it.
Putting everything together to get what you want, considering an element in an arbitrary screen position (the red border):
var elemento = document.querySelector('#meuElemento');
var boxDoElemento = elemento.getBoundingClientRect();
elemento.onmousemove = function(e) {
var rolamentoX = document.body.scrollLeft;
var rolamentoY = document.body.scrollTop;
var posX = e.clientX - boxDoElemento.left + rolamentoX;
var posY = e.clientY - boxDoElemento.top + rolamentoY;
elemento.innerHTML = posX + ', ' + posY;
}
#meuElemento {
width: 50%;
height: 250px;
margin-left: 25%;
margin-top: 100px;
border: 1px solid red;
}
<div id="meuElemento">passe o mouse aqui dentro</div>
Thank you, I have my example here: http://jsfiddle.net/7gsn30xr/7/ I can get the values for the objects, but I cannot get the values for the objects.
– akm
Your SVG occupies the entire screen and is in position
0,0
, but the X and Y axes are shifted. You need to consider these shifts. Also, my answer is about screen coordinates, but your chart uses Cartesian coordinates. It seems to me a problem more complex and totally different from what I understood from your question...– bfavaretto
Okay, I’m going to try to create the Cartesian coordinates. Open a new topic unless I come up with a solution. With this example how can I disable mouse lines when exiting the chart?
– akm
@akm in the
elemento.onmouseout
you can hide them by settingstyle.display = 'none'
in the elements that make the lines (I’m guessing you’re talking about my other answer, which has these lines...)– bfavaretto
Yes it is the other question of the cursor, I used condition if you pass such pixels, it is hidden.
– akm