2012-10-23 29 views
2

AS。我想旋转一个物体,但我不希望它将它移动到任何地方,只需旋转它并将其保留就位。函数绘制只画出矩形。如何在HTML5中旋转对象以保持原样

<!DOCTYPE html> 
    <html> 
     <head> 
      <script> 
      var ctx, canvas; 

       window.onload = function(){ 
        canvas = document.getElementById('myCanvas'); 
        ctx = canvas.getContext('2d'); 
        //sciana 


         draw(); 


       } 
      function draw() { 
        //ctx.scale(0.5,0.5); 
        ctx.rotate(Math.PI /6);//here I rotate but it moves... 
        ctx.fillRect(100, 100, 50, 50); 


        } 

      </script> 
     </head> 
     <body> 
      <canvas id="myCanvas" width="600" height="600" style="background-color:#D0D0D0"> 
       Twoja przeglądarka nie obsługuje elementu Canvas. 
      </canvas> 
     </body> 
    </html> 

回答

1
Draw - with shape centered at 0,0 
Rotate 
Translate - to cx,cy , where cx,cy is the center of the shape, where it is to be located. 

为了达到这种效果,你必须做的函数调用的确切顺序相反的2D背景的,像这样:

context.translate(cx, cy); 
context.rotate (radians); 
context.fillRect (x, y, width, height); 
0

只需使用CSS3的rotate属性即可。

-webkit-transform: rotate(7.5deg); 
    -moz-transform: rotate(7.5deg); 
     -ms-transform: rotate(7.5deg); 
     -o-transform: rotate(7.5deg); 
      transform: rotate(7.5deg); 

通过CSSPlease

0

在画布上的旋转功能围绕原点旋转,为了你身边需要翻译的形状,你要绘制的心形状的中心旋转,然后旋转,然后绘制形状。

你最后的代码可能是这个样子:

<!DOCTYPE html> 
<html> 
    <head> 
     <script> 
     var ctx, canvas; 

      window.onload = function(){ 
       canvas = document.getElementById('myCanvas'); 
       ctx = canvas.getContext('2d'); 
       //sciana 


       draw(); 


      } 
      function draw() { 
      //ctx.scale(0.5,0.5); 
       ctx.translate(125, 125); 
       ctx.rotate(Math.PI /6);//here I rotate but it moves... 
       ctx.fillRect(-25, -25, 50, 50); 

      } 

     </script> 
    </head> 
    <body> 
     <canvas id="myCanvas" width="600" height="600" style="background-color:#D0D0D0"> 
      Twoja przegladarka nie obsluguje elementu Canvas. 
     </canvas> 
    </body> 
</html> 
+0

是否有一般公式? – user1769735

+0

在上面的示例中,我将它翻译为125,125,这是您之前尝试绘制矩形的中心。如果你想在不同的地方绘制它,你可以放置不同的坐标。 我将fillRect中的坐标更改为-25,-25,因此中心将位于0,0处,原点已被转换为125,125。 您可以在任意点绘制一个形状,而不必转换为另一点。 –