2012-05-01 71 views
0

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

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

当我点击左上角点我在控制台500弄〜数量,而不是零...什么,我需要做的就是在画布上鼠标的坐标?

回答

1

这是因为你正在获取页面坐标。我猜你想在你的两个画布中的任何一个画布中放置当前的鼠标位置?希望这将解决您的问题:

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

而且这个计算器与你相似,并可能给你一个更好的理解: 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); 
}); 
3

你应通过减去事件偏移(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); 
+0

+1为了得到弥补,除非你需要支持旧的浏览器,我建议使用'element.getBoundingClientRect();'返回顶部与底部的对象左,右属性 – UpTheCreek

0

我使用此代码和它的作品完美的我。一旦添加,画布鼠标事件就有两个新属性: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); 
} 
+0

我修复处理直接与画布本身,而不触及上下文。 –