我不确定为什么总是收到错误消息“无法读取未定义的clientX属性。
我的理解是event.clientX应该给我x坐标,event.clientY应该给我坐标。
请您告诉我我要去哪里了吗?
var canvas = document.getElementById('myCanvas');
function getMousePos(event,canvas) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
return { // the getMousePos function returns an object. It’s a factory
x: mx,
y: my,
}
}
var mousePos = getMousePos(event, canvas);
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
答案 0 :(得分:0)
在这一行:
var mousePos = getMousePos(event, canvas);
您正在传递未定义的变量event
。正如redouglas所说,您必须在实际的mouse event
getMousePos
正确的脚本应该是:
var canvas = document.getElementById('myCanvas');
function getMousePos(event, canvas) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
var mousePos = {
x: mx,
y: my,
}
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
}
canvas.addEventListener("mousemove", function(event) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
var mousePos = {
x: mx,
y: my,
}
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
});
但是,这取决于您的需求,建议您查看链接的MDN资源。
答案 1 :(得分:0)
您不能简单地将任意event
参数传递给函数。您需要告诉javascript,此函数侦听画布上的鼠标事件。为此,您可以将其添加为event listener:
var mousepos;
var canvas = document.getElementById('myCanvas');
function getMousePos(event) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
mousepos = {
x: mx,
y: my,
}
console.log(mousepos);
}
canvas.addEventListener("mousemove",getMousePos);
<canvas id = "myCanvas"></canvas>
只要用户将鼠标移到画布上,就会触发mouseOver
事件。由于我们已分配getMousePos
来监听此事件,因此javascript自动传递了event
参数,现在我们可以读取相关属性。每当用户移动鼠标时,我们console.log()
的位置。