简体   繁体   English

在HTML5画布上移动时跟踪鼠标坐标的简单方法

[英]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? 在HTML5画布上移动鼠标时,是否有一种简单的方法来获取相对鼠标坐标?

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? 在使用画布来简化此类操作时,是否有使用框架(例如Kinetic)的原因?

If you're not using your mousemove on your canvas use this: 如果您不在画布上使用mousemove ,请使用以下命令:

$(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. 您可以绝对定位画布,然后删除while循环。

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 . 并涵盖所有情况:如果画布具有fixed位置,则无需考虑滚动: pageXOffsetpageYOffset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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