Skip to main content
PATurmel12
Inspiring
August 8, 2018
Answered

Finding mouse position on canvas. Is there a better way?

  • August 8, 2018
  • 2 replies
  • 4398 views

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?

This topic has been closed for replies.
Correct answer ClayUUID

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.

2 replies

ClayUUIDCorrect answer
Legend
August 8, 2018

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.

PATurmel12
Inspiring
August 8, 2018

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.

Legend
August 9, 2018

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.

ankushr40215001
Inspiring
August 8, 2018

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.

Hope this helps.

Thanks!

Ankush