HTML5画布中旋转矩形内的鼠标位置
Mouse position within rotated rectangle in 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;
}
经过进一步的工作,我得出了以下解决方案,我想我会在这里转录出来,供将来可能需要它的人使用:
// 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;
}
相关文章:
- 跟踪jqplot垂直折线图的鼠标位置
- Javascript-在视频中跟踪鼠标位置
- 打开相对于鼠标位置的CSS3/HTML5模式对话框
- 如何控制quadraticCurve使用鼠标位置控制位置
- Javascript如何在不使用画布的情况下获取鼠标位置
- jQuery根据鼠标位置计算DIV偏移量和边界
- 在火狐浏览器的画布上获取鼠标位置
- 尝试绘制从鼠标位置工具栏中选择的形状 - HTML5 CANVAS
- 添加视图框时更改鼠标位置
- 如何在鼠标位置获取所有元素
- Three.js 3D缩放到鼠标位置
- 将鼠标位置(0,0)设置为画布的中心
- Unity 2d实例化鼠标位置问题,请告知
- 在原生JavaScript中获取画布中鼠标位置的最现代方法
- 如何在 Javascript 中正确获取鼠标位置
- 如何将元素移动到鼠标位置
- 使用 JavaScript 跟踪 Adobe Air 中的鼠标位置
- 三.js - 对象跟随鼠标位置
- 绘制在鼠标位置折叠的水平线和垂直线
- 在鼠标按下期间获取鼠标位置