Update (5/5/16): patriques' answer should be used instead, as it's both simpler and more reliable.
(更新 (5/5/16):应该使用爱国者的答案 ,因为它既简单又可靠。)
Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top
doesn't always return what you need.
(由于画布并非总是相对于整个页面设置样式,所以canvas.offsetLeft/Top
并不总是返回所需的内容。)
It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div
element containing the canvas with a position: relative
style applied.(它将返回相对于其offsetParent元素偏移的像素数,该像素数可以像是div
元素,其中包含具有position: relative
的画布position: relative
样式。)
To account for this you need to loop through the chain of offsetParent
s, beginning with the canvas element itself.(为了解决这个问题,您需要遍历offsetParent
的链,从canvas元素本身开始。)
This code works perfectly for me, tested in Firefox and Safari but should work for all.(该代码非常适合我,已在Firefox和Safari中进行了测试,但应该适用于所有人。)
function relMouseCoords(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
The last line makes things convenient for getting the mouse coordinates relative to a canvas element.
(最后一行使获取鼠标相对于画布元素的坐标变得很方便。)
All that's needed to get the useful coordinates is(获得有用的坐标所需要的是)
coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…