【问题标题】:Collision detection on rotated image in javascriptjavascript中旋转图像的碰撞检测
【发布时间】:2013-04-13 14:50:49
【问题描述】:

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

}

谢谢:)

【问题讨论】:

  • 出于好奇,如果您只需要旋转,为什么不使用 CSS 变换?
  • 如果您可以访问 html 画布,则可以访问为您旋转图像的 css 动画。

标签: html image math canvas rotation


【解决方案1】:

[编辑: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(rotation) 或 Math.cos(rotation) 变为负数,您需要在 BB 计算中使用它们之前获取它们的绝对值。这就是为什么您的计算在 PI * 1.5 时变得疯狂的原因。

【讨论】:

  • 感谢您的帮助,但我知道如何绘制旋转图像,但我需要一个函数来返回旋转后的精灵以查找新宽度和高度的碰撞。
  • 碰撞检测(!?)...这对您提出的问题非常有用:p 好的,请参阅我编辑的答案以获取您的旋转边界框。
  • 感谢您的帮助,很抱歉我没有写任何关于碰撞检测的内容,我已经编辑了问题。
  • @markE,能否请您在参数中添加XY轴点和返回值?谢谢
猜你喜欢
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多