单击画布时获取鼠标坐标

时间:2017-04-02 18:40:01

标签: canvas coordinates mouse

一个常见问题,但我仍然需要帮助。当有人在画布中点击时,我正试图获取并存储鼠标坐标。

我的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中。

2 个答案:

答案 0 :(得分:11)

您可以使用MouseEvent

offsetXoffsetY属性来实现这一目标

//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>

答案 1 :(得分:3)

我正在使用这段代码。

&#13;
&#13;
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);
&#13;
<canvas width="400" height="400" id="canvas" style="background-color: lightblue"></canvas>
&#13;
&#13;
&#13;