0

我正在尝试围绕中心点旋转球(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 度角传来并停止?http://jsfiddle.net/MmjZk/

4

1 回答 1

0

哎呀,你有一个错字:

y1 = ball.x - cy,

应该:

y1 = ball.y - cy,

但是你让球几乎在画布内旋转(注意球只在画布的 4 个角上旋转进入视野)

这是一些替代代码,可以使球旋转更紧密。这是一个小提琴:http: //jsfiddle.net/m1erickson/dFctW/

<!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>
于 2013-03-16T17:58:30.763 回答