问题描述
我创建了一个将鼠标坐标转换为画布像素坐标的函数:
I made a function that transforms mouse coordinates to canvas pixel coordinates:
/* 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];
}
你可以看到。问题是图像的解决方案无效。
You can see demonstration of the pixel coordinate calculation. The problem is that the solutions fails for images having border
property set.
如何从矩形中减去边框宽度?性能确实很重要,因为此计算通常在鼠标移动事件期间执行。
How can I subtract the border width from rectangle? Performance does matter, as this calculation is often performed during mouse move events.
推荐答案
getComputedStyle
包含您想要的信息:
getComputedStyle
contains the information you desire:
在应用开始时获取一次边框信息设置画布边框后。
Fetch the border information once at the beginning of your app after the canvas border has been set.
// get a reference to the canvas element
var canvas=document.getElementById('yourCanvasId');
// get its computed style
var styling=getComputedStyle(canvas,null);
// fetch the 4 border width values
var topBorder=styling.getPropertyValue('border-top-width');
var rightBorder=styling.getPropertyValue('border-right-width');
var bottomBorder=styling.getPropertyValue('border-bottom-width');
var leftBorder=styling.getPropertyValue('border-left-width');
如果您在app-wide范围内设置这些边框宽度变量,则可以在HTMLCanvasElement中使用这些预取变量.prototype.relativeCoords。
If you scope these border-width variables app-wide, you can use these prefetched variables in your HTMLCanvasElement.prototype.relativeCoords.
祝你的项目好运!
这篇关于获取没有边框的边界客户端矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!