Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

javascript - 如何获得在画布元素上单击鼠标的坐标?(How do I get the coordinates of a mouse click on a canvas element?)

What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

(将click事件处理程序添加到canvas元素(将返回click的x和y坐标)(相对于canvas元素)的最简单方法是什么?)

No legacy browser compatibility required, Safari, Opera and Firefox will do.

(不需要旧版浏览器兼容性,Safari,Opera和Firefox都可以。)

  ask by Tom translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...