HTML5 Canvas鼠标坐标

时间:2012-05-01 19:36:50

标签: javascript html5 canvas onclick mouseevent

我有一个带有<canvas>元素的HTML文件,我试图在click事件中获取鼠标坐标。我正在使用此代码:

secondCanvas.addEventListener('click', function(e) {
    console.log(e.pageX)
}, false);

当我点击左上角时,我进入控制台500~数字,而不是零...我需要做什么才能在画布上获得鼠标的坐标?

3 个答案:

答案 0 :(得分:2)

您应该通过从事件偏移(e.pageXe.pageY)中减去画布元素偏移来计算画布鼠标位置。
这是一个link,解释了如何在dom中获取元素位置,代码应如下所示:

secondCanvas.addEventListener('click', function(e) {
   var pos = {
       x : e.pageX - canvasOffsetX,
       y : e.pageY - canvasOffsetY
   };
   console.log(pos.x)
}, false);

答案 1 :(得分:0)

这是因为你得到了页面坐标。我猜你想在你的两个画布中的任何一个画布中想要当前的鼠标位置?希望这能解决您的问题:

http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

此stackoverflow也与您的类似,可能会让您更好地理解: Tracking mouse position in canvas when no surrounding element exists

用户解决方案:lwburk

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

$('#canvas').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coordinateDisplay = "x=" + x + ", y=" + y;
    writeCoordinateDisplay(coordinateDisplay);
});

答案 2 :(得分:-1)

我使用此代码,它对我来说非常适合。添加后,canvas鼠标事件有两个新属性:canvasX和canvasY,它们已正确映射。在获得canvas元素之后,不要忘记调用canvas.extendMouseEvents()并且您已经开始营业了。

HTMLCanvasElement.prototype.extendMouseEvents = function() {
    this.mapMouseEvent = function(ev) {
        var r = this.getBoundingClientRect();
        ev.canvasX = ev.pageX - r.left;
        ev.canvasY = ev.pageY - r.top;
    };
    this.addEventListener("mousemove", this.mapMouseEvent);
    this.addEventListener("click", this.mapMouseEvent);
    this.addEventListener("contextmenu", this.mapMouseEvent);
    this.addEventListener("dblclick", this.mapMouseEvent);
    this.addEventListener("mousedown", this.mapMouseEvent);
    this.addEventListener("mouseenter", this.mapMouseEvent);
    this.addEventListener("mouseleave", this.mapMouseEvent);
    this.addEventListener("mouseover", this.mapMouseEvent);
    this.addEventListener("mouseout", this.mapMouseEvent);
    this.addEventListener("mouseup", this.mapMouseEvent);
}