2011-08-19 5 views
5

캔버스의 "회전"기능을 사용하여 원점을 중심으로 회전하지 않고 이미지의 중심을 중심으로 이미지를 회전하려면 어떻게해야합니까? 붉은 광장은 0,0에 orgin는 주위에 회전이 예에서HTML5 캔버스로 이미지 회전

<html> 
    <head></head> 
    <body> 
     <canvas id="tmp" style="width: 300px; height: 300px; border: 1px red solid" /> 
     <script type="text/javascript"> 
      var deg = 0; 

      function Draw() { 
       var ctx = document.getElementById('tmp').getContext('2d'); 

       ctx.save(); 
       ctx.fillStyle = "white"; 
       ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height); 
       ctx.fillStyle = "red"; 

       ctx.rotate(deg * 0.0174532925199432957); //Convert to rad's 
       ctx.fillRect(50, 50, 20, 20); 
       ctx.restore(); 

       deg+=5; 

       setTimeout("Draw()", 50); 
      } 

      Draw(); 
     </script> 
    </body> 
</html> 

:

는 다음과 같은 예를 생각해 보자. 그 중심을 중심으로 사각형을 회전시키고 싶다고합시다. 그럼 다음과 같이 그것을 뒤로 이동 다시 번역을 사용 회전 원점으로 이동 변환 사용하려고했습니다

 ctx.translate(-(50 + 10), -(50 + 10)); //Move to origin 
     ctx.rotate(deg * 0.0174532925199432957); //rotate 
     ctx.translate(50, 50); //move back to original location 
     ctx.fillRect(50, 50, 20, 20); 
     ctx.restore(); 

을하지만 이전의 번역과하지에 우선 변환 함수 호출처럼 보인다 변환을 결합하십시오. 그렇다면 어떻게하면 좋을까요?

답변

8

찾고 계신 제품 : jsFiddle? 당신이 큰 소수 대신 Math.PI/180를 사용해야합니다

//Move to center of rectangle 
ctx.translate(60, 60); 
ctx.rotate(deg * 0.0174532925199432957); //rotate 
//Draw rectangle 
ctx.fillRect(-10, -10, 20, 20); 
ctx.restore(); 

참고.
또한 widthheight을 캔버스에 올바르게 설정하고 setTimeouteval()으로 변경했습니다.