矩形在 html5 Canvas 中的旋转以弧度存储。为了确定随后的鼠标点击是否在任何给定的矩形内,我将鼠标 x 和 y 平移到矩形的旋转原点,将旋转的反向应用到鼠标坐标,然后将鼠标坐标平移回来。
这根本行不通 - 鼠标坐标未按预期进行转换(即,在旋转矩形的可见边界内单击时不在原始矩形的边界内),并且针对矩形边界的测试失败.鼠标点击检测仅在矩形的最中心区域有效。请查看下面的代码片段,并告诉我您是否可以看出这里出了什么问题。
// Our origin of rotation is the center of the rectangle
// Our rectangle has its upper-left corner defined by x,y, its width
// defined in w, height in h, and rotation(in radians) in r.
var originX = this.x + this.w/2, originY = this.y + this.h/2, r = -this.r;
// Perform origin translation
mouseX -= originX, mouseY -= originY;
// Rotate mouse coordinates by opposite of rectangle rotation
mouseX = mouseX * Math.cos(r) - mouseY * Math.sin(r);
mouseY = mouseY * Math.cos(r) + mouseX * Math.sin(r);
// Reverse translation
mouseX += originX, mouseY += originY;
// Bounds Check
if ((this.x <= mouseX) && (this.x + this.w >= mouseX) && (this.y <= mouseY) && (this.y + this.h >= mouseY)){
return true;
}
最佳答案
经过一些进一步的工作,得出了以下解决方案,我想我会在这里为将来可能需要它的任何人转录:
// translate mouse point values to origin
var dx = mouseX - originX, dy = mouseY - originY;
// distance between the point and the center of the rectangle
var h1 = Math.sqrt(dx*dx + dy*dy);
var currA = Math.atan2(dy,dx);
// Angle of point rotated around origin of rectangle in opposition
var newA = currA - this.r;
// New position of mouse point when rotated
var x2 = Math.cos(newA) * h1;
var y2 = Math.sin(newA) * h1;
// Check relative to center of rectangle
if (x2 > -0.5 * this.w && x2 < 0.5 * this.w && y2 > -0.5 * this.h && y2 < 0.5 * this.h){
return true;
}
关于javascript - HTML5 Canvas 中旋转矩形内的鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9202006/