HTML5 Canvas : How to handle mousedown mouseup mouseclick

Go To StackoverFlow.com

13

I been playing around with html5 canvas and ran into a problem.

canvas.onmousedown = function(e){
        dragOffset.x = e.x - mainLayer.trans.x;
        dragOffset.y = e.y - mainLayer.trans.y;
        canvas.onmousemove = mouseMove;
}
canvas.onmouseup = function(e){
    canvas.onmousemove = null;
}

canvas.onmouseclick = mouseClick;

function mouseMove(e){
    mainLayer.trans.x = e.x - dragOffset.x;
    mainLayer.trans.y = e.y - dragOffset.y;
    return false;
}

function mouseClick(e){
    // click action
}

In this code, I make my mouse click+drag pan the canvas view by translating by the drag offset. But I also have a click event. Right now, whenever I drag my mouse and let go, it runs both onmouseup AND onclick.

Are there any techniques to make them unique?

2012-04-03 20:58
by AlexCheuk
Check this out! http://stackoverflow.com/questions/7224175/html5-canvas-mouse/11027438#1102743 - Munkh 2012-06-14 05:58


14

A click event happens after a successful mousedown and mouseup on an element. Is there any particular reason you are using click on top of the mouse events? You should be fine with just mousedown/mouseup, click is a convenience event that saves you a little bit of coding.

I would generally do it this way:

var mouseIsDown = false;

canvas.onmousedown = function(e){
    dragOffset.x = e.x - mainLayer.trans.x;
    dragOffset.y = e.y - mainLayer.trans.y;

    mouseIsDown = true;
}
canvas.onmouseup = function(e){
    if(mouseIsDown) mouseClick(e);

    mouseIsDown = false;
}

canvas.onmousemove = function(e){
    if(!mouseIsDown) return;

    mainLayer.trans.x = e.x - dragOffset.x;
    mainLayer.trans.y = e.y - dragOffset.y;
    return false;
}

function mouseClick(e){
    // click action
}
2012-04-05 21:47
by Colin Godsey


0

Try declaring a variable such as clickStatus = 0; and at the start of each function check to ensure the correct value.

if (clickstatus == 0) {
     clickstatus =1;
     ...//function code
 };
2012-04-03 21:03
by RyanS


0

in the function mouse move set a boolean to say that a move occured, encompase all the code in mouseup and click with an if statement to check that a drag did not occur. After these if statements and before the end of the functions set the dragging boolean to false.

2012-04-03 21:03
by awiebe