javascript中旋转图像的碰撞检测

时间:2013-04-12 19:00:22

标签: html5 image math canvas rotation

我已经创建了一个js函数,该函数应该旋转图像以进行碰撞检测,但是当旋转超过π* 1.5(Pi)时,该函数不能正常工作,图像将被裁剪。

function rotateImage(image , rotation)
{

    // Creates a canvas
    var rotatedImage = document.createElement( "canvas" ) . getContext( "2d" ),

    // Setting a bounding box size
    boundingWidth = Math . abs( image . height * Math . cos( rotation ) + image . width * Math . sin( rotation ) ),
    boundingHeight = Math . abs( image . height * Math . sin( rotation ) + image . width * Math . cos( rotation ) );

    // Changing canvas size
    rotatedImage . canvas.width = boundingWidth;
    rotatedImage . canvas.height = boundingHeight;

    // Translating canvas
    rotatedImage . translate( boundingWidth/2 , boundingHeight/2 );

    // Rotate canvas
    rotatedImage . rotate( rotation );

    // Un-translating canvas
    rotatedImage . translate( -boundingWidth/2 , -boundingHeight/2 );

    // Draws image
    rotatedImage . drawImage( image , 0 , 0 );

    // Returns canvas
    return rotatedImage . canvas;

}

谢谢:)

1 个答案:

答案 0 :(得分:3)

[编辑:OP澄清他们想要碰撞检测]

哦......你想要一个旋转矩形的边界框用于碰撞检测。

您不需要使用画布旋转,只需使用三角函数!

// where w = rectangle width (sprite width)
// where h = rectangle height (sprite height)
// where a = angle of rotation in degrees
// calculate the bounding box of the rectangle at the given rotation

function BoundingBoxDimensions(w,h,a){
  var rads=a*Math.PI/180;
  var c = Math.abs(Math.cos(rads));
  var s = Math.abs(Math.sin(rads));
  return({  width: h * s + w * c,  height: h * c + w * s });
}

关于上面的代码,如果你的Math.sin(旋转)或Math.cos(旋转)变为负数,你需要在BB计算中使用它们之前取其绝对值。这就是为什么你的计算在PI * 1.5上疯狂的原因。