我有以下函数来获取鼠标单击位置(坐标)。
$('#myCanvas').on('click', function(e) {
event = e;
event = event || window.event;
var canvas = document.getElementById('myCanvas'),
x = event.pageX - canvas.offsetLeft,
y = event.pageY - canvas.offsetTop;
alert(x + ' ' + y);
});
我需要获取单击某个位置时的鼠标点以及拖动该位置后的第二个鼠标指针位置。
IE。,
mousedown 点和 mouseup 点。
尝试一些不同的设置:
var canvas = myCanvas; //store canvas outside event loop
var isDown = false; //flag we use to keep track
var x1, y1, x2, y2; //to store the coords
// when mouse button is clicked and held
$('#myCanvas').on('mousedown', function(e){
if (isDown === false) {
isDown = true;
var pos = getMousePos(canvas, e);
x1 = pos.x;
y1 = pos.y;
}
});
// when mouse button is released (note: window, not canvas here)
$(window).on('mouseup', function(e){
if (isDown === true) {
var pos = getMousePos(canvas, e);
x2 = pos.x;
y2 = pos.y;
isDown = false;
//we got two sets of coords, process them
alert(x1 + ',' + y1 + ',' +x2 + ',' +y2);
}
});
// get mouse pos relative to canvas (yours is fine, this is just different)
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
那么为什么我们要听鼠标松开的声音window
?如果您将鼠标移到canvas
然后释放鼠标按钮,该事件将不会注册到canvas
。所以我们需要倾听一个全球事件,例如window
.
由于我们已经标记了我们的isDown
在鼠标按下事件中,我们知道接下来的鼠标按下“属于”画布(当我们检查isDown
flag).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)