如何获得鼠标单击画布元素的坐标?将Click事件处理程序添加到画布元素以返回单击的x和y坐标(相对于画布元素)的最简单方法是什么?不需要传统浏览器兼容性,Safari、Opera和Firefox就行了。
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
var x;var y;if (e.pageX || e.pageY) { x = e.pageX; y = e.pageY;}else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } x -= gCanvasElement.offsetLeft;y -= gCanvasElement.offsetTop;
饮歌长啸
TA贡献1951条经验 获得超3个赞
canvas.offsetLeft/Top
div
position: relative
offsetParent
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;
coords = canvas.relMouseCoords(event);canvasX = coords.x;canvasY = coords.y;
添加回答
举报
0/150
提交
取消