Stack Overflow 上有很多关于如何获取 Canvas 元素上的事件相对于 Canvas 本身的坐标的答案。我正在使用以下解决方案getEventPosition
(
/**** This solution gives me an offset equal to the border size
**** when the canvas has a border. Example:
**** <canvas style='border: 10px solid black; background: #333;' id='gauge_canvas' width='500' height='500'></canvas>
****/
// Get DOM element position on page
this.getPosition = function(obj) {
var x = 0, y = 0;
if (obj.offsetParent) {
do {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
} while (obj);
}
return {'x': x, 'y': y};
};
// Get mouse event position in DOM element (don't know how to use scale yet).
this.getEventPosition = function(e, obj, aux_e, scale) {
var evt, docX, docY, pos;
evt = (e ? e : window.event);
if (evt.pageX || evt.pageY) {
docX = evt.pageX;
docY = evt.pageY;
} else if (evt.clientX || evt.clientY) {
docX = evt.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
docY = evt.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
// This works on hammer.js
else if (typeof aux_e !== 'undefined') {
docX = aux_e.touches[0].x;
docY = aux_e.touches[0].y;
}
pos = this.getPosition(obj);
if (typeof scale === 'undefined') {
scale = 1;
}
return {'x': (docX - pos.x) / scale, 'y': (docY - pos.y) / scale};
};
由于此代码属于我的库,并且可以采用用户提供的任何画布元素,因此当用户为库提供带边框的画布时,事情就会破裂。有没有考虑到边界的解决方案?