簡體   English   中英

使用鼠標在HTML5 Canvas中拖動元素

[英]Dragging an element in HTML5 Canvas using mouse

我創建了一個小程序,在其中顯示一個圓圈,並允許用戶在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)中將if內部for循環更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM