【问题标题】:canvas get points on mouse events画布获取鼠标事件点
【发布时间】:2023-04-09 07:39:01
【问题描述】:

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

$('#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 点。

【问题讨论】:

标签: jquery canvas mouseevent coordinates


【解决方案1】:

尝试一些不同的设置:

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 标志时)。

【讨论】:

    【解决方案2】:

    使用像 $('#myCanvas').mousedown 和 $('#myCanvas').mouseup 这样的接收器

    【讨论】:

      【解决方案3】:

      那么,你需要拖放吗?嗯,这很容易:首先你检测到'onclick',如果你的目标(矩形,圆等)保存点到变量,'onmousemove'你正在移动对象,然后'onmousedown'你得到最后一点.

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 2012-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 2014-05-29
        • 1970-01-01
        相关资源
        最近更新 更多