2013-04-12 33 views
0

我創建了一個js函數,它應該爲碰撞檢測旋轉圖像,但函數不能正確工作,當旋轉超過π* 1.5(Pi)時,圖像作物。在javascript中旋轉圖像的碰撞檢測

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; 

} 

謝謝:)

+5

出於好奇,如果旋轉是所有你需要爲什麼不使用CSS變換? –

+4

如果您有權訪問HTML畫布,則可以訪問將爲您旋轉圖像的CSS動畫。 – runspired

回答

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上瘋狂的原因。

+0

感謝您的幫助,但我知道我如何繪製旋轉的圖像,但我需要一個函數返回旋轉的精靈來查找新的寬度和高度的碰撞。 – Mathematica

+0

碰撞檢測(!?)...這將是有用的信息,把你的問題:p好了,看我編輯的答案來獲得你的旋轉邊界框。 – markE

+0

感謝您的幫助,並且抱歉我沒有寫關於碰撞檢測的任何內容,我編輯了這個問題。 – Mathematica