2013-04-12 4 views
0

충돌 감지를 위해 이미지를 회전해야하는 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; 

} 

감사합니다 :)

+5

호기심 때문에 회전이 필요한 경우 CSS 변환을 사용하지 않는 것이 좋을까요? –

+4

html 캔버스에 액세스 할 수 있으면 이미지를 회전시키는 CSS 애니메이션에 액세스 할 수 있습니다. – runspired

답변

3

는 [편집 : 영업 이익은 충돌 감지 할 명확히]

이 오 ... 당신이 회전 된 사각형의 경계 상자는 충돌 감지에 사용하고자합니다.

캔버스 회전을 사용할 필요가 없습니다. 삼각법을 사용하십시오! 당신으로, Math.sin (회전)이나와 Math.cos (회전) 부정적인 가면

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

, 위의 코드에 대해서는, 당신은 당신의 BB 계산에 사용하기 전에 자신의 절대 값을 할 것입니다. 그래서 계산이 PI * 1.5에 미친 이유입니다.

+0

도와 줘서 고마워하지만 난 회전 된 이미지를 그릴 수있는 방법을 알고 있지만 새로운 너비와 높이의 충돌을 찾기 위해 회전 된 스프라이트를 반환하는 함수가 필요합니다. – Mathematica

+0

충돌 감지 (!?) ... 질문에 넣는 데 유용한 정보 였을 것입니다. p OK, 내 수정 된 답변을 참조하여 회전 된 경계 상자를 얻으십시오. – markE

+0

도움을 주셔서 감사합니다. 미안하지만 충돌 감지에 대해 아무 것도 쓰지 않습니다. 질문을 편집했습니다. – Mathematica

관련 문제