简体   繁体   中英

Simple way to track mouse coordinates while moving over HTML5 canvas

Is there a simple way to get relative mouse coordinates while moving mouse over HTML5 canvas?

I found this:

function getMousePos(canvas, evt){
    // get canvas position
    var obj = canvas;
    var top = 0;
    var left = 0;
    while (obj && obj.tagName != 'BODY') {
        top += obj.offsetTop;
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }

    // return relative mouse position
    var mouseX = evt.clientX - left + window.pageXOffset;
    var mouseY = evt.clientY - top + window.pageYOffset;
    return {
        x: mouseX,
        y: mouseY
    };
}

But it seems too heavy to me. Is there a reason using frameworks (like Kinetic) when working with canvas to simplify such things?

If you're not using your mousemove on your canvas use this:

$(function () { 
canvas = document.getElementById('canvas');
canvas.onmousemove = mousePos;
 });

function mousePos(e) {
    if (e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if (e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }
}

You could position canvas absolutely and then remove while loop.

Ultimately, if canvas would not move, you could cache it's offset and then use cached value.

And to cover all cases: if canvas would have fixed position, you'll need not consider scrolling: pageXOffset , pageYOffset .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM