javascript - 使用鼠标拖动 HTML5 Canvas 中的元素

标签 javascript html canvas

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

我能够显示圆圈,但只有当我单击圆圈的右下角时,拖动功能才起作用,如果我尝试通过单击圆圈的其他任何位置来拖动它,那么它就不起作用。我不知道如何解决其中的问题。

这是我的完整代码:

<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) ,但我无法弄清楚如何修复坐标,这样如果我单击圆圈的任何位置,它应该可拖动。

最佳答案

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

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

关于javascript - 使用鼠标拖动 HTML5 Canvas 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161804/

相关文章:

javascript - 为什么类中的事件处理程序不从该类继承变量

javascript - 对过滤器索引使用react更新状态

javascript - 使用MongoDb和Node.js来组织代码

html - 位置 :relative not working in IE9?

html - CSS 叠加效果

javascript - 如何防止 Chartjs 条形图中的侧边栏被剪切?

javascript - JS Canvas - 保存透明图像

javascript - 如何使用 Javascript 在 html 文件中搜索字符串?

javascript - 在 html 代码中使用多个 jquery 和 javascript

javascript - 将 JavaScript 鼠标事件从一个元素传播到另一个元素?