canvas get points on mouse events

允我心安 提交于 2019-12-06 06:27:25

问题


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.

ie., mousedown point and mouseup points.


回答1:


Try a little different setup:

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

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.

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).




回答2:


use receivers like $('#myCanvas').mousedown and $('#myCanvas').mouseup




回答3:


So, you need drag'n'drop? Well, it's very easy: first you detect 'onclick' if point inside of your target (rect, circle, whatever) save point to variable , 'onmousemove' you're moving the object and then 'onmousedown' you're getting last point.

Hope it will help you!



来源:https://stackoverflow.com/questions/17343358/canvas-get-points-on-mouse-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!