使用鼠标在HTML5 Canvas中拖动元素

时间:2015-07-01 12:49:28

标签: javascript html5 canvas

我创建了一个小程序,我在其中显示一个圆圈,允许用户在HTML5画布中拖动圆圈。

我能够显示圆圈,但只有当我点击我的圆圈右下角时拖动功能才有效,如果我尝试通过点击圆圈的任何其他位置拖动它然后它无法正常工作。我无法弄清楚如何解决问题。

这是我的完整代码:

<script>
// handle mousedown events
function myDown(e) {

    // tell the browser we're handling this mouse event
    e.preventDefault();
    e.stopPropagation();

    // get the current mouse position
    var mx = parseInt(e.clientX - offsetX);
    var my = parseInt(e.clientY - offsetY);

    // test each circle to see if mouse is inside
    dragok = false;
    for (var i = 0; i < circles.length; i++) {
        var r = circles[i];
        if (mx > r.x && mx < r.x + r.radius && my > r.y && my < r.y + r.height) {
            // if yes, set that circles isDragging=true
            dragok = true;
            r.isDragging = true;
        }
    }
    // save the current mouse position
    startX = mx;
    startY = my;
}


// handle mouseup events
function myUp(e) {  
    // tell the browser we're handling this mouse event
    e.preventDefault();
    e.stopPropagation();

    // clear all the dragging flags
    dragok = false;
    for (var i = 0; i < circles.length; i++) {
        circles[i].isDragging = false;
    }
}


// handle mouse moves
function myMove(e) {
    // if we're dragging anything...
    if (dragok) {

        // tell the browser we're handling this mouse event
        e.preventDefault();
        e.stopPropagation();

        // get the current mouse position
        var mx = parseInt(e.clientX - offsetX);
        var my = parseInt(e.clientY - offsetY);

        // calculate the distance the mouse has moved
        // since the last mousemove
        var dx = mx - startX;
        var dy = my - startY;

        // move each circle that isDragging 
        // by the distance the mouse has moved
        // since the last mousemove
        for (var i = 0; i < circles.length; i++) {
            var r = circles[i];
            if (r.isDragging) {
                r.x += dx;
                r.y += dy;
            }
        }

        // redraw the scene with the new circle positions
        draw();

        // reset the starting mouse position for the next mousemove
        startX = mx;
        startY = my;

    }
}
</script>

我想,问题出在function myDown(e),但我无法弄清楚如何修复坐标,这样如果我点击圈子的任何位置,它就应该是可拖动的。

1 个答案:

答案 0 :(得分:1)

尝试将函数myDown(e)中的if for for循环更改为:

if (mx > r.x - r.radius && mx < r.x + r.radius && my > r.y - r.radius && my < r.y + r.radius)