本文介绍了HTML5 Canvas:如何处理mousedown mouseup mouseclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用html5画布玩弄一个问题。

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
}

在这段代码中,我通过拖动偏移进行鼠标单击+拖动平移画布视图。但我也有一个点击事件。现在,每当我拖动鼠标,放开,它会同时运行onmouseup和onclick。

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?

推荐答案

mousedown mouseup 成功后,元素。在鼠标事件之上,您是否有任何特定的原因使用点击?您应该可以使用 mousedown / mouseup 是一个方便的事件,节省了一些编码。

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.

我通常这样做:

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
}

这篇关于HTML5 Canvas:如何处理mousedown mouseup mouseclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 14:56