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
What's the Significant Use of Unary Plus and Minus Operators
How to Fire and Forget a Promise in Nodejs (Es7)
Using "Object.Create" Instead of "New"
Youtube Iframe API: How to Control an Iframe Player That's Already in the HTML
Pass Props to Parent Component in React.Js
Why Was the Arguments.Callee.Caller Property Deprecated in JavaScript
Difference Between Settimeout with and Without Quotes and Parentheses
Allow Google Chrome to Use Xmlhttprequest to Load a Url from a Local File
How to Check If a Checkbox Is Checked
How to Access Iframe Elements with JavaScript
Prevent Execution of Parent Event Handler
Sort Array by Firstname (Alphabetically) in JavaScript
Insert HTML at Caret in a Contenteditable Div
Webdriver Click() VS JavaScript Click()
Determining Image File Size + Dimensions via JavaScript
Stop Execution of JavaScript Function (Client Side) or Tweak It