2012-02-08 21 views
2

html5キャンバス内の矩形の回転はラジアンで格納されています。次のマウスクリックが特定の矩形内にあるかどうかを調べるために、マウスxとyを矩形の回転の原点に変換し、回転の逆をマウス座標に適用し、マウス座標を元に戻します。HTML5キャンバスで回転した矩形内のマウスの位置

これは単純に機能しません - マウス座標が予想通りに変換されていない(回転している矩形の目に見える範囲内をクリックすると元の矩形の境界内にはない)、矩形の境界に対してテストする失敗する。マウスクリックの検出は、四角形の最も中央の領域内でのみ機能します。下記のコードスニペットを見て、あなたが何が間違っているかを見てください。さらにいくつかの作業の後

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

答えて

8

、私は将来的にそれを必要とするかもしれない人のためにここに書き写すと思った次のソリューションとなりました:

// 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; 
    } 
関連する問題