Differencebetween Screenx/Y, Clientx/Y and Pagex/Y

Why does the clientX and Y change on scroll?

pageX and pageY:

Relative to the top left of the fully rendered content area in the browser. This reference point is below the url bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

So use pageX and pageY instead of clientX/Y:

  var mX = (event.pageX - left) - width / 2;
var mY = (event.pageY - top) - height / 2;

for more detail read difference between clientX/Y and pageX/Y?

clientX and clientY are offset from reall coordinates

.clientX and .clientY are provided relative to the "client area", the portion of the page you are currently viewing. You'll need to make adjustments to take into account the canvas element's position relative to the client area. Fortunately, you're also provided with .getBoundingClientRect() which provides an element's location and dimensions in client area coordinates.

Putting this together, you can modify your .onmousemove code as in:

  var bounding = c.getBoundingClientRect();
var x = event.clientX - bounding.left;
var y = event.clientY - bounding.top;

Difference between 'x' and 'clientX' property of event in javascript

The MouseEvent.x property is an alias for the MouseEvent.clientX property. See MDN docs : https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/x



Related Topics



Leave a reply



Submit