Copy link to clipboard
Copied
I have a canvas 2000 px wide, which fits the width of the client window.
If I use a mouse event with event.clientX I must calculate the relative position with respect to the window width.
If I use a mouse event with event.clientY I must calculate the relative position with respect to the window width plus offset due to the scrolling of the window.
$(canvas).mousedown(grdown.bind(this));
function grdown(e){
var rect = canvas.getBoundingClientRect();
console.log("clientX " + (e.clientX * (2000/canvas.width)) + " clientY " + ((e.clientY * (2000/canvas.width))-rect.top * (2000/canvas.width) ) );
} // this eventListener is done with jQuery
Is there a simpler way to do this?
1 Correct answer
Why on Earth are you using jQuery? Canvas mode's API has a full-featured mouse event system built right in.
EaselJS v1.0.0 API Documentation : MouseEvent
EaselJS Tutorial: Mouse Interaction
Example code for reporting mouse click location:
stage.addEventListener("stagemousedown", mouseClicked);
function mouseClicked(evt) {
console.log(evt.stageX, evt.stageY);
}
If the canvas can scale, just divide the coordinates by stage.scaleX and stage.scaleY to get normalized values.
Copy link to clipboard
Copied
Hi PATurmel12,
I am just a beginner with Js and AS coding. However tried to find out some relevant information for you.
Please check out the below links and see if they can trigger some idea in your mind with respect to the codes.
- Get the mouse coordinates when clicking on canvas - Stack Overflow
- javascript - Getting mouse position in canvas after movement - Stack Overflow
Hope this helps.
Thanks!
Ankush
Copy link to clipboard
Copied
Why on Earth are you using jQuery? Canvas mode's API has a full-featured mouse event system built right in.
EaselJS v1.0.0 API Documentation : MouseEvent
EaselJS Tutorial: Mouse Interaction
Example code for reporting mouse click location:
stage.addEventListener("stagemousedown", mouseClicked);
function mouseClicked(evt) {
console.log(evt.stageX, evt.stageY);
}
If the canvas can scale, just divide the coordinates by stage.scaleX and stage.scaleY to get normalized values.
Copy link to clipboard
Copied
Thanks for you response,
JQuery gives a much more responsive web page.
Your suggestion of using stage.scaleX does not allow for the offset due to scrolling.
Copy link to clipboard
Copied
You said you wanted to find the mouse position on the canvas. That's what the code I posted does.
> Your suggestion of using stage.scaleX does not allow for the offset due to scrolling.
I have no idea what this is supposed to mean. Scaling and scrolling are completely different things.

