Canvas How to - Move rectangle along a Circle








Question

We would like to know how to move rectangle along a Circle.

Answer


<!--  ww  w .j  av a  2  s  . c  om-->
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {  
        var canvas = $("#myCanvas");
        var context = canvas.get(0).getContext("2d");
          
        var canvasWidth = canvas.width();
        var canvasHeight = canvas.height();
        
        var playAnimation = true;
        
        var startButton = $("#startAnimation");
        var stopButton = $("#stopAnimation");
        
        startButton.hide();
        startButton.click(function() {
          $(this).hide();
          stopButton.show();
          
          playAnimation = true;
          animate();
        });
        
        stopButton.click(function() {
          $(this).hide();
          startButton.show();
          
          playAnimation = false;
        });
        
        // Class that defines new shapes to draw
        var Shape = function(x, y, width, height) {
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
          
          this.radius = Math.random()*30;
          this.angle = 0;
        };
        
        // Array that holds all the shapes to draw
        var shapes = new Array();
        shapes.push(new Shape(10, 10, 100, 100));
        // Animation loop that does all the fun stuff
        function animate() {
          // Clear
          context.clearRect(0, 0, canvasWidth, canvasHeight);
          
          // Loop through every object
          var shapesLength = shapes.length;
          for (var i = 0; i < shapesLength; i++) {
            var tmpShape = shapes[i];
            // Update
            // Circular orbit
            var x = tmpShape.x+(tmpShape.radius*Math.cos(tmpShape.angle*(Math.PI/180)));
            var y = tmpShape.y+(tmpShape.radius*Math.sin(tmpShape.angle*(Math.PI/180)));
            
            // Increase the angle on the circular orbit
            tmpShape.angle += 5;
            if (tmpShape.angle > 360) {
              tmpShape.angle = 0;  
            };          
            
            // Draw
            context.fillRect(x, y, tmpShape.width, tmpShape.height);
          };
          
          if (playAnimation) {
            // Run the animation loop again in 33 milliseconds
            setTimeout(animate, 33);
          };
        };
        
        // Start the animation loop
        animate();
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
    </canvas>
    <div>
      <button id="startAnimation">Start</button>
      <button id="stopAnimation">Stop</button>
    </div>
  </body>
</html>

The code above is rendered as follows: