Html javascript中旋转图像的碰撞检测

Html javascript中旋转图像的碰撞检测,html,image,math,canvas,rotation,Html,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

我已经创建了一个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;

}

谢谢:)

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

Ohhh…您希望在碰撞检测中使用旋转矩形的边界框

不需要使用画布旋转,只需使用三角法即可

// 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时变得疯狂

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

Ohhh…您希望在碰撞检测中使用旋转矩形的边界框

不需要使用画布旋转,只需使用三角法即可

// 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时变得疯狂

出于好奇,如果旋转是您所需要的,为什么不使用CSS转换?如果您可以访问html画布,您可以访问将为您旋转图像的CSS动画。出于好奇,如果旋转是您所需要的,为什么不使用CSS转换?如果您可以访问html画布,您可以访问将为您旋转图像的css动画。感谢您的帮助,但我知道如何绘制旋转图像,但我需要一个函数,返回旋转的精灵以查找新宽度和高度的碰撞。碰撞检测(!?)…这将是在您的问题中输入的有用信息:p确定,请参阅我编辑的答案以获得旋转的边界框。谢谢您的帮助,很抱歉我没有写任何关于碰撞检测的内容,我已经编辑了这个问题。@马克,您能在参数中添加XY轴点和返回值吗?感谢您的帮助,但我知道如何绘制旋转图像,但我需要一个函数,返回旋转的精灵以查找新宽度和高度的碰撞。碰撞检测(!?)…这将是在您的问题中输入的有用信息:p好的,请参阅我编辑的答案以获取旋转的边界框。感谢您的帮助,很抱歉,我没有写任何关于碰撞检测的内容,我已经编辑了这个问题。@markE,你能在参数中添加XY轴点和返回值吗?谢谢