Get mouse coordinates when clicking on canvas

A common question, but I still need help. I try to get and save the coordinates of the mouse when someone clicks on the canvas.

my html

<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>

and my javascript

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");

guessX = 0;//stores user click on canvas
 guessY = 0;//stores user click on canvas

function storeGuess(event){
    var x = event.clientX - ctx.canvas.offsetLeft;
    var y = event.clientY - ctx.canvas.offsetTop;
    /*guessX = x;
    guessY = y;*/


    console.log("x coords:" + x + ", y coords" + y);

I read a lot of forums, w3schools and videos on this. I am close to understanding this, but I have missed something. I can get the page coordinates if I delete ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But I need to somehow enable them in order to get the coordinates of the canvas, and then save them into guessX variables and guess.

+4
source share
2 answers

You can achieve this by using and property offsetX offsetYMouseEvent

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");
guessX = 0; //stores user click on canvas
guessY = 0; //stores user click on canvas
function storeGuess(event) {
    var x = event.offsetX;
    var y = event.offsetY;
    guessX = x;
    guessY = y;
    console.log("x coords: " + guessX + ", y coords: " + guessY);
}
<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick="storeGuess(event)"></canvas>
Run codeHide result
+6
source

.

var myCanvas = document.querySelector('#canvas');

myCanvas.addEventListener('click', function(event) {
    var rect = myCanvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y); 
}, false);
<canvas width="400" height="400" id="canvas" style="background-color: lightblue"></canvas>
Hide result
0

Source: https://habr.com/ru/post/1673830/


All Articles