gpt4 book ai didi

jquery - Canvas 在鼠标事件上获取点

转载 作者:行者123 更新时间:2023-12-01 00:45:04 25 4
gpt4 key购买 nike

我有以下函数来获取鼠标单击位置(坐标)。

$('#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);
});

我需要在单击某个位置时获取鼠标点,并在拖动相同位置后获取第二个鼠标点位置。

即,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
};
}

那么我们为什么要监听窗口上的鼠标松开呢?如果您将鼠标悬停在 canvas 之外,然后释放鼠标按钮,则该事件不会在 canvas 中注册。因此我们需要监听一个全局事件,例如window

由于我们已经在鼠标按下事件中标记了 isDown ,因此我们知道接下来的鼠标松开“属于” Canvas (当我们检查 isDown 标志时)。

关于jquery - Canvas 在鼠标事件上获取点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17343358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com