【发布时间】:2014-11-29 15:58:29
【问题描述】:
我做了一个将鼠标坐标转换为画布像素坐标的函数:
/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
var x,y;
//This is the current screen rectangle of canvas
var rect = this.getBoundingClientRect();
//Recalculate mouse offsets to relative offsets
x = event.clientX - rect.left;
y = event.clientY - rect.top;
//Also recalculate offsets of canvas is stretched
var width = rect.right - rect.left;
//I use this to reduce number of calculations for images that have normal size
if(this.width!=width) {
var height = rect.bottom - rect.top;
//changes coordinates by ratio
x = x*(this.width/width);
y = y*(this.height/height);
}
//Return as an array
return [x,y];
}
您可以看到pixel coordinate calculation 的演示。问题是图像having border property set的解决方案失败。
如何从矩形中减去边框宽度?性能确实很重要,因为此计算通常在鼠标移动事件期间执行。
【问题讨论】:
-
请查看stackoverflow.com/questions/13607252/…获取有效的边框宽度计算
标签: javascript html5-canvas coordinates dom-events