Canvas 方法围绕点旋转,html画布

Canvas 方法围绕点旋转,html画布,canvas,rotation,Canvas,Rotation,我试着绕着一个中心点旋转一个球(cx,cy)。 当我这样做时: (function keepDrawing(){ context.clearRect(0, 0, w, h); ball.x = cx+Math.cos(angle); ball.y = cy+Math.sin(angle); angle += 0.1; ball.draw(context); setTimeout(keepDrawing, 40); }()); 它是有效的,

我试着绕着一个中心点旋转一个球
(cx,cy)
。 当我这样做时:

 (function keepDrawing(){
    context.clearRect(0, 0, w, h);

    ball.x = cx+Math.cos(angle);
    ball.y = cy+Math.sin(angle);

    angle += 0.1;
    ball.draw(context);
    setTimeout(keepDrawing, 40);
 }());
它是有效的,但因为我刚刚开始学习这个,我尝试了另一种方法,它并没有产生我所想的

 (function keepDrawing(){
    context.clearRect(0, 0, w, h);


    var x1 = ball.x - cx,
        y1 = ball.x - cy,
        x2 = x1*Math.cos(angle) - y1*Math.sin(angle),
        y2 = y1*Math.cos(angle) + x1*Math.sin(angle);


    ball.x = cx + x2;
    ball.y = cy + y2;
    ball.draw(context);
    setTimeout(keepDrawing, 40);
}());
球从左上角45度角射出并停止

哎呀,你有一个打字错误:

y1 = ball.x - cy,
应该是:

y1 = ball.y - cy,
但是,球在画布内几乎不旋转(请注意,球仅在画布的4个角上旋转到视图中)

这里有一些备用代码,可以更紧密地旋转球。这是一把小提琴:


正文{背景色:象牙;}
画布{边框:1px纯红;}
$(函数(){
功能球(半径、颜色){
这个半径=半径| | 25;
this.color=color | |'#'+(Math.random()*0xFFFFFF
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){
    function Ball(radius, color){
      this.radius = radius || 25;
      this.color = color || '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      this.startingX;
      this.startingY;
      this.x = 0;
      this.y = 0;
      this.rotation = 0;
    }


    Ball.prototype.draw = function(context){
      context.save();
      context.fillStyle = this.color;
      context.beginPath();
      context.arc(this.x, this.y, this.radius, 0, Math.PI*2)
      context.fill();
      context.restore();
    };

    var canvas = document.getElementById('canvas'),
          log = document.getElementById('log'),
      context = canvas.getContext('2d'),
      w = canvas.width,
      h = canvas.height,
          ball = new Ball(),
          angle = 3*Math.PI/180,
          cx = w/2,
          cy = h/2;
          ball.startingX=cx;
          ball.startingY=cy-60;

      (function keepDrawing(){

          context.clearRect(0, 0, w, h);    

          // increase the angle of rotation
          angle+=6*Math.PI/180;

          // calculate the new ball.x / ball.y
          var x1 = ball.startingX - cx;
          var y1 = ball.startingY - cy;
          ball.x =cx+ x1*Math.cos(angle) - y1*Math.sin(angle);
          ball.y =cy+ y1*Math.cos(angle) + x1*Math.sin(angle);
          ball.draw(context);

          setTimeout(keepDrawing, 40)
      }());



}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>