2011-08-19 18 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(); 

しかし、translate関数の呼び出しは、以前の翻訳オーバーライドしていないように見える:私はそのようにようにそれを戻すために再度変換し使用後、回転の原点に移動するために翻訳を使用しようとしました変換を結合する。どのように私は望む効果を達成するのですか?

答えて

8

これはあなたが探しているものですか:jsFiddle

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

大規模小数点の代わりにMath.PI/180を使用する必要があります。
キャンバスにもwidthheightを正しく設定し、setTimeouteval()に変更しました。