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 に答える