Tutorial Canvas Animation: bouncing

Je browser ondersteunt geen Canvas. Update je browser naar de laatste versie.

Zwaartekracht met stuitereffect

HTML code for this animation:

  <!doctype html>
  <html>
  <head>
 	 <title>Het Canvas eenparig versnelde beweging</title>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
	 <script src="js/scripts.js"></script>
  </head>
  <body> 
 	 <canvas id="gravity_bounce_canvas" style="border: 1px solid;">
    Your browser does not support Canvas. Update your browser to the latest version.
    </canvas>
  </body>
  </html>

Javascript code in scripts.js

$(document).ready(function() {
	gravitybounce();
});

function checkForCanvasSupport() {
  return !!document.createElement('some_canvas').getContext;
  }
  
function gravityBounce(){
   
   var radius=15;
   var speedfactor =7;
  // define the direction the ball is moving
   var degrees = 305;
   var angle = degrees * Math.PI/ 180;
   var vx = Math.cos(angle) * speedfactor/2;
   var vy  = Math.sin(angle) * speedfactor;
   var gravity = 0.1;
   //var canvas=document.getElementById("gravity_canvas");
   //var context=canvas.getContext("2d");
   var canvas=$("#gravity_bounce_canvas");
   var context = canvas.get(0).getContext("2d");
   // define the coordinates of the starting point p0
   var p0 = {x:20,y:canvas.height()-radius};
   // define the start coordinates, the speed and the radius of the ball
   var ball = {x:p0.x, y:p0.y, vx:vx, vy:vy, radius:radius};
   
  if (!checkForCanvasSupport) {
      return;
  }
  init();
  
  function init()
      {
      setInterval(draw, 12);
      }
	  
      function draw(){
		ball.vy += gravity;
		if ((ball.y + ball.radius) > canvas.height()){
		   ball.vy = -(ball.vy)
		}
		
		if((ball.x + ball.radius) > canvas.width()  ){
		ball.vx= -(ball.vx);
		ball.vy = -(ball.vy);
		}
		
		if((ball.x - ball.radius) < 0){
		ball.vx= -(ball.vx);	
		}
		ball.y += ball.vy;
		ball.x += ball.vx;
		
		context.clearRect(0,0, 636,288);
     	context.fillStyle = "#f16529";
		context.lineWidth=7;
        context.strokeStyle="black";
      	context.beginPath();
      	context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
      	context.closePath();
      	context.fill();
		context.stroke();
	}	     
}

To next tutorial

Leave a comment