Reputation: 143
A common question, but I still need help. I'm trying to get and store the mouse coordinates when someone clicks within 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's click on canvas
guessY = 0;//stores user's 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've read loads of forums, w3schools, and videos on this. I'm close to figuring it out, but I'm missing something. I can get the coordinates of the page if I delete the ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But i need to incorporate those somehow to get the coordinates of the canvas, and then store then into the variables guessX and guessY.
Upvotes: 11
Views: 20589
Reputation: 11942
The accepted answer is correct till the canvas is not fit inside a content.
A more generic solution need to convert mouse event in the canvas geometry.
const canvasSetup = document.getElementById("puppyCanvas");
const ctx = canvasSetup.getContext("2d");
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
guessX = 0; //stores user's click on canvas
guessY = 0; //stores user's click on canvas
function storeGuess(event) {
guessX = parseInt(event.offsetX*canvasSetup.width/canvasSetup.offsetWidth);
guessY = parseInt(event.offsetY*canvasSetup.height/canvasSetup.offsetHeight);
console.log(`coords:${guessX}x${guessY}`);
ctx.strokeRect(guessX,guessY,1,1);
}
<div style="height:200px;">
<canvas id="puppyCanvas" style="background-color: lightgrey;height:100%;" width="500" height="500" onclick="storeGuess(event)"></canvas>
</div>
Upvotes: 2
Reputation: 61
I am using this piece of code.
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>
Upvotes: 4
Reputation: 32869
You could achieve that by using the offsetX
and offsetY
property of MouseEvent
//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");
guessX = 0; //stores user's click on canvas
guessY = 0; //stores user's 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>
Upvotes: 15