canvas获取鼠标事件点 [英] canvas get points on mouse events

查看:602
本文介绍了canvas获取鼠标事件点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having the following function to get the mouse click positions(coordinates).

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

    });

我需要在点击位置时获得鼠标点, 。

I need to get the mouse point on clicking a position and also secound mouse point position after draging the same.


mousedown点和鼠标点。

ie., mousedown point and mouseup points.

推荐答案

尝试一些不同的设置:

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;
        y3 = 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
    };
}

那么我们为什么要在窗口上看鼠标呢?如果鼠标在画布外,然后释放鼠标按钮,事件将不会注册到画布。因此我们需要听一个全局事件,如窗口。

So why do we listen to mouse up on the window? If you mouse outside the canvas and then release the mouse button, the event won't be registered with the canvas. So we need to listen to a global event such as the window.

因为我们已经标记了 isDown 鼠标按下事件我们知道以下鼠标向上属于画布(因为我们检查 isDown 标志)。

Since we already have marked our isDown at the mouse down event we know that that the following mouse up "belongs" to the canvas (as we check the isDown flag).

这篇关于canvas获取鼠标事件点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆