鼠标在HTML5 Canvas中旋转矩形内的位置 [英] Mouse position within rotated rectangle in HTML5 Canvas

查看:36
本文介绍了鼠标在HTML5 Canvas中旋转矩形内的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html5画布中矩形的旋转以弧度存储.为了确定随后的鼠标单击是否在任何给定的矩形内,我将鼠标x和y转换为矩形的旋转原点,将旋转的反向应用于鼠标坐标,然后再将鼠标坐标转换回去.

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;
}

推荐答案

经过进一步的工作,得出了以下解决方案,我认为我会在这里为将来可能需要的任何人转录:

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:

// 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;
    }

这篇关于鼠标在HTML5 Canvas中旋转矩形内的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆