Tutorial Canvas Animation: spiral movement

Check this example in your browser

For a spiral movement, we can use the script for a circular motion from the previous tutorial, except that we increase (or decrease) the radius of the turning circle. To display the path through again, we have added a "bread crumb" trail.

HTML code for this animation:

<!doctype html>
<html>
<head>
<title>Canvas: spiral movement</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="js/service.js"></script>
<script src="js/ball.js"></script>
<script src="js/functions.js"></script>
</head>
<script>
    jQuery(document).ready(function(){
    spiralMotion1();
    });	>
</script>
<body> 
<canvas id="spiral_motion1" style="border: 1px solid;"></canvas>
</body>
</html>

Javascript:

function spiralMotion1(){
  var degrees = 0;
  var Angle;
  var rotationRadius=2;
  var rotationRadiusIncrease = 1;
  var ballRadius=20
  var centerX;
  var centerY;
  var x;
  var y;
  var animate=true;
  var breadcrumbs = new Array();
  var crumbRadius=1;
  var canvas = jQuery("#spiral_motion1");
  var context = canvas.get(0).getContext("2d");
  //function Ball(x,y,radius,color,strokeColor,lineWidth) in ball.js
  var ball_3 = new Ball(-10,-10,20,'#f16529','#000',7);
  var parentWidth=jQuery(canvas).parent().width();
  var canvasWidth=context.canvas.width = parentWidth;
  var canvasHeight=context.canvas.height= 288;
  
  if (!checkForCanvasSupport) {
  return;
  }
  
  (function drawFrame() {
  window.requestAnimationFrame(drawFrame, canvas);
  
  
  if(animate){
  context.clearRect(0,0,canvasWidth,canvasHeight); // clear canvas
  //Make the Canvas element responsive for desktop, tablet and smartphone.
  centerX = canvasWidth/2;
  centerY = canvasHeight/2
  Angle = degrees * (Math.PI / 180);
  degrees = degrees + 1;
  ball_3.x=rotationRadius * Math.cos(setAngle()) + centerX;
  ball_3.y=rotationRadius * Math.sin(setAngle()) + centerY;
  ball_3.draw(context);
  
  //add a breadcrumb to the breadcrumbs array
  breadcrumbs.push({x:ball_3.x,y:ball_3.y});
  //draw the breadcrumbs that shows the track of the movement 
  context.globalCompositeOperation = "destination-over";
  showBreadcrumbs(breadcrumbs);
  
  rotationRadius += rotationRadiusIncrease/5
  if ((ball_3.y + ballRadius+4) > canvas.height()){ 
  animate=false; 
  }
  }
  }());//end drawFrame
 function setAngle(){
  Angle = degrees * (Math.PI / 180);
  degrees = degrees + 2;
  return Angle;
  }//end setAngl()
  
  function showBreadcrumbs(breadcrumbs){
  for (var i = 0; i< breadcrumbs.length; i++) {
  context.beginPath();
  context.arc(breadcrumbs[i].x,breadcrumbs[i].y,crumbRadius,0, 2*Math.PI,false);
  context.closePath();
  context.fillStyle="#999";
  context.fill();
  }
  }//end showBreadcrumbs()
}//end spiralMotion1()


Next tutorial

Leave a comment