一个常见问题,但我仍然需要帮助。当有人在画布内单击时,我试图获取并存储鼠标坐标。
我的 HTML
<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>
和我的 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);
我阅读了大量相关论坛、w3schools 和视频。我即将弄清楚,但我错过了一些东西。如果删除ctx.canvas.offsetLeft和ctx.canvas.offsetTop,我可以获得页面的坐标。但我需要以某种方式合并这些来获取画布的坐标,然后将其存储到变量guessX和guessY中。
您可以通过使用 offsetX
的
offsetY
和
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>
我正在使用这段代码。
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>
接受的答案是正确的,直到画布不适合内容。
更通用的解决方案需要转换画布几何中的鼠标事件。
const canvasSetup = document.getElementById("puppyCanvas");
const ctx = canvasSetup.getContext("2d");
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(`x coords:${guessX}x${guessY}`);
}
<div style="height:100px;">
<canvas id="puppyCanvas" style="border:2px solid black;height:100%;" width="500" height="500" onclick="storeGuess(event)"></canvas>
</div>