How to create bouncing balls using html5 canvas

how to make bouncing balls in html5 canvas using javascript - Nibunan

how to create bouncing balls in html5 canvas using javascript - Nibunan

how to write program to display bouncing balls in html5 canvas using javascript - Nibunan

how to write program to create bouncing balls animation in html5 canvas using javascript - Nibunan

how to write code to create bouncing balls effect in html5 canvas using javascript - Nibunan

Html5 canvas is evolving to give the rich graphics on browser without using flash or other plugins. Html5 canvas is being used in many places like games animations and rich user interfaces on web and so on.This airticle explains how to create the bouncing balls sprite animations in html5 canvas using javascript.

Demo

Open with new tab

Source

Source code contains three main parts. The main html that creates the bouncing balls and adds it to the viewport, Viewport and Bouncing ball objects. Code has been clearly explained by the comment lines so that it would be easy to understand.


      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <title>Creating Bouncing balls using html5 canvas - Nibunan</title>
      </head>
      <body style="margin: 0px">
      <canvas width="700" height="450" id="drawing-surface"></canvas>
      <script type="text/javascript">

      //It is the global function to generate the Random Number with range
      //If range is 10, It will create the Random integer between 1 to 10
      function Random(range) {
      return Math.floor((Math.random() * range) + 1);
      }

      //Create viewport that holds all the graphics objects (bouncing balls) 
      //and triggers the paint event at frame rate 40/s
      var viewport = new Viewport();
      
      //Create hundred bouncing balls with random location, random direction
      //and random speed. Add those balls to viewport using addObject function
      //that is defined in viewport object
      for (var i = 0; i < 100; i++) {
      var ball = new BouncingBall();
      ball.location = { x: Random(window.innerWidth - 32), y: Random(window.innerHeight - 32) };
      ball.direction = { x: Random(1), y: Random(1) };
      ball.speed = Random(5)+2;
      viewport.addObject(ball);
      }
      
      //Start rendering by calling init function of viewport object      
      viewport.init();
      </script>
      </body>
      </html>
    

Viewport

Viewport holds all the bouncing ball objects and triggers the paint event at frame rate 40 /s to create the smooth animation. It works on top of canvas that is included in the body of the html with id 'drawing-surface'.


      function Viewport() {
      var me = this;
      
      //Initialize objects collection 
      me.objects = [];
      
      var canvas = document.getElementById("drawing-surface");
      
      //function that resizes the canvas to window size whenever required
      function resizeCanvas() {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      }
      resizeCanvas();
      
      //resize the canvas when window getting resized
      window.onresize = function () {
      resizeCanvas();
      }      
      
      //get the canvas context to draw 2d objects
      var drawingSurface = document.getElementById("drawing-surface").getContext("2d");
      
      //create the background image for the viewport
      var image = new Image();
      image.src = "background.png";
      image.onload = function () {
      me.backgroundImage = image;
      me.doPaint = true;
      }
      
      me.doPaint = true;
      
      //Function that paints the background image
      function drawBackgroundImage() {
      if (me.backgroundImage) {
      drawingSurface.drawImage(me.backgroundImage, 0, 0, canvas.width, canvas.height);
      }
      }
      
      //Function that triggers the paint event for all the objects in the collection
      function drawObjects() {
      for (var i = 0; i < me.objects.length; i++) {
      me.objects[i].paint(drawingSurface);
      }
      }

      //paintInit funtion is invoked before paint event. If doPaint is false,
      //it will not trigger the paint event for child objects.
      me.paintInit = function () {
      me.doPaint = true;
      }
      
      //paint function is triggered at rate 40 /s to create the animation
      function paint() {
      me.paintInit();
      if (me.doPaint) {
      drawBackgroundImage();
      drawObjects();
      me.doPaint = false;
      }
      }
      
      
      var timer;
      //start the animation
      me.init = function () {
      timer = setInterval(function () { paint(); }, 1000 / 40);
      };
      
      me.repaint = function () {
      me.doPaint = true;
      };
      
      //adds the object into collection
      me.addObject = function (obj) {
      me.objects.push(obj);
      }      
      }
    

Bouncing Ball

Bouncing ball is the object that paints the bouncing ball and moves it with particular direction and speed. Whenever the paint event triggered by the viewport it changes its location based on direction and speed to create the smooth movement of the ball.


      function BouncingBall() {
      var me = this;
      me.speed = 5;
      me.location = { x: 0, y: 0 };
      var image = new Image();
      image.src = "ball.png";
      image.onload = function () {
      me.image = image;
      }
      me.move = function () {
      var ball = me;
      switch (ball.direction.x) {
      case 0:
      if (ball.location.x <= 0) {
      ball.direction.x = 1;
      ball.location.x += ball.speed;
      }
      else {
      ball.location.x -= ball.speed;
      }
      break;
      case 1:
      if (ball.location.x >= window.innerWidth - 32) {
      ball.direction.x = 0;
      ball.location.x -= ball.speed;
      }
      else {
      ball.location.x += ball.speed;
      }
      break;
      }
      switch (ball.direction.y) {
      case 0:
      if (ball.location.y <= 0) {
      ball.direction.y = 1;
      ball.location.y += ball.speed;
      }
      else {
      ball.location.y -= ball.speed;
      }
      break;
      case 1:
      if (ball.location.y >= window.innerHeight - 32) {
      ball.direction.y = 0;
      ball.location.y -= ball.speed;
      }
      else {
      ball.location.y += ball.speed;
      }
      break;
      }
      }
      me.paint = function (context) {
      if (me.image) {
      me.move();
      context.drawImage(me.image, me.location.x, me.location.y);
      }
      }
      }