HTML5 Canvas 中旋转矩形内的鼠标位置
html5 画布内矩形的旋转以弧度存储。为了确定后续的鼠标单击是否在任何给定的矩形内,我将鼠标 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;
}
Rotation of rectangles within an html5 canvas is being stored in radians. In order to find whether subsequent mouse clicks are within any given rectangle, I am translating the mouse x and y to the origin of rotation for the rectangle, applying the reverse of the rotation to the mouse coordinates, and then translating the mouse coordinates back.
This simply isn't working - mouse coordinates are not being transformed as expected (that is, not within the bounds of the original rectangle when clicking within the visible bounds of the rotated rectangle), and testing against the rectangle's bounds is failing. Detection of mouse clicks works only within the centre-most area of the rectangle. Please see the code snippet below and tell me if you can see what's wrong here.
// 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过进一步的工作,得出以下解决方案,我想我会将其转录在这里供将来可能需要它的任何人使用:
After some further work, came to the following solution, which I thought I'd transcribe here for anyone who might need it in the future: