Jquery 画布获取鼠标事件的点数

Jquery 画布获取鼠标事件的点数,jquery,canvas,mouseevent,coordinates,Jquery,Canvas,Mouseevent,Coordinates,我有以下功能来获取鼠标点击位置(坐标) 我需要在点击一个位置时获得鼠标点,并在拖动相同的位置后再次找到鼠标点位置 即。, 鼠标点和鼠标点。使用像$('myCanvas')这样的接收器。鼠标点和$('myCanvas')。鼠标点那么,你需要拖放吗?这很简单:首先,如果目标内部的点(矩形、圆形等)将点保存为变量,则检测“onclick”,然后“onmousemove”移动对象,然后“onmousedown”获取最后一个点 希望它能帮助你 尝试不同的设置: var canvas = myCanvas;

我有以下功能来获取鼠标点击位置(坐标)

我需要在点击一个位置时获得鼠标点,并在拖动相同的位置后再次找到鼠标点位置

即。,
鼠标点和鼠标点。

使用像$('myCanvas')这样的接收器。鼠标点和$('myCanvas')。鼠标点

那么,你需要拖放吗?这很简单:首先,如果目标内部的点(矩形、圆形等)将点保存为变量,则检测“onclick”,然后“onmousemove”移动对象,然后“onmousedown”获取最后一个点


希望它能帮助你

尝试不同的设置:

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
    };
}
那么为什么我们要在
窗口上听鼠标的声音呢?如果将鼠标移到
画布
之外,然后释放鼠标按钮,则事件将不会在
画布
中注册。因此,我们需要收听全局事件,如
窗口

由于我们已经在鼠标下降事件中标记了我们的
isDown
,我们知道接下来的鼠标上升“属于”画布(当我们检查
isDown
标志时)。

可能重复的
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
    };
}