Tutorial Canvas Animation: removing and regenerating objects

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

In a canvas animation you create a space for your objects. By default this is the entire canvas element, but it can also be a section of the canvas, or even an area that is larger than the canvas. Because the objects are moving, they will encounter the boundaries of the canvas after after a certain time period and abandoned the canvas. If they have left the canvas there are several options: you can forget about the objects, put them back on the canvas or you can follow them. In this tutorial we will look at these options.

Example1. Removing an object (ball) from the canvas system

GOOD TO KNOW

The ball must be completely outside the canvas before you remove it.

HTML

  <!doctype html>
  <html>
  <head>
  <title>Removing an object (ball) from the canvas system</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>
 
  <body> 
  <canvas id="remove_ball" style="border: 1px solid;" >
  Removing an object (ball) from the canvas system
  </canvas>
  </body>
  </html>

Javascript

   $(document).ready(function() {
	removeBall();
  });
 
function removeBall(){
  
  var canvas = jQuery('#remove_ball'),
  context = canvas.get(0).getContext('2d');
  parentWidth=jQuery(canvas).parent().width();
  var canvasWidth=context.canvas.width = parentWidth;
  var canvasHeight=context.canvas.height = 288;
  var logBallsAmount = jQuery('textarea#log');
  balls = [];
  numBalls = 10;
  
  for (var ball, i = 0; i < numBalls; i++) {
  ball = new Ball();
  ball.id = "ball" + i;
  ball.x  = Math.random() * canvas.width();
  ball.y  = Math.random() * canvas.height();
  ball.vx = Math.random() * 2 - 1;
  ball.vy = Math.random() * 2 - 1;
  balls.push(ball);
  }
 function draw (ball, pos) {
      ball.x += ball.vx;
      ball.y += ball.vy;
      if (ball.x - ball.radius > canvasWidth ||
      ball.x + ball.radius < 0 ||
      ball.y - ball.radius > canvasHeight ||
      ball.y + ball.radius < 0) {
      balls.splice(pos, 1); //remove ball from array
  
  	  if (balls.length > 0) {
      //een textarea bevat text of html, en geen value zoals bij een input element
      //Daarom gebruiken we de text() of html() function in plaats van de val() function
      logBallsAmount.text("Removed " + ball.id)
      } else {
      logBallsAmount.text("All gone!")
      }
  }
  ball.draw(context);
  }
  (function drawFrame () {
      window.requestAnimationFrame(drawFrame, canvas);
      context.clearRect(0, 0, canvasWidth, canvasHeight);
      var i = balls.length;
      while (i--) {
      draw(balls[i], i);
  }
  }());
};

Example 2. Removal and show up (regenerate) of an object (ball) on the Canvas

The next method to treat an object that is outside is the repositioning of the object. The idea behind this is that when the object moves outside the canvas and is no longer needed, you can put it on a new position as if it were a completely new object. This gives you a regular supply of objects (a maximum is set) without running the risk of having to deal with an excessive number of objects, that slows down the browser.

This technique is useful when you want to create fountains or other particle systems where there is a stream of objects that are constantly 'sprayed'. The mechanism of regeneration is similar to that of removal (Example 1); you wait until the object is leaving the canvas, but instead of removing it, you move it elsewere.

Removing an object (ball) from the canvas system Your browser does not support Canvas. Update your browser to the latest version.

HTML

  <!doctype html>
  <html>
  <head>
  <title>Removal and show up (regenerate) of an object (ball) on the Canvas</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>
  <script>
      $(document).ready(function() {
        removeAndRegenerateBall();
      });
  </script>
  </head>
  <body> 
  <canvas id="remove_ball" style="border: 1px solid;" >
 Removal and show up (regenerate) of an object (ball) on the Canvas
  </canvas>
  </body>
  </html>

Javascript

function removeAndRegenerateBall(){
    var canvas = jQuery('#remove_regenerate_ball');
    var context = canvas.get(0).getContext('2d');
    var parentWidth=jQuery(canvas).parent().width();
    var canvasWidth=context.canvas.width = parentWidth;
    var canvasHeight=context.canvas.height = 288;
    var balls2 = [];
    var numBalls = 80;
    var gravity = 0.5;
    for (var ball2, i = 0; i < numBalls; i++) {
    //function Ball (x,y,radius,color,strokeColor,lineWidth)
    ball2 = new Ball(2, Math.random() * 0xffffff,20,'#a3caff','#f16529',1);
    ball2.x = canvasWidth / 2;
    ball2.y = canvasHeight;
    ball2.vx = Math.random() * 2 - 1;
    ball2.vy = Math.random() * -10 - 10;
    balls2.push(ball2);
    }
    
    function draw (ball2) {
    ball2.vy += gravity;
    ball2.x += ball2.vx;
    ball2.y += ball2.vy;
    if (ball2.x - ball2.radius > canvasWidth ||
    ball2.x + ball2.radius < 0 ||
    ball2.y - ball2.radius > canvasHeight ||
    ball2.y + ball2.radius < 0) {
    ball2.x = canvasWidth / 2;
    ball2.y = canvasHeight;
    ball2.vx = Math.random() * 2 - 1;
    ball2.vy = Math.random() * -10 - 10;
    }
    ball2.draw(context);
    }
    
    (function drawFrame2 () {
    window.requestAnimationFrame(drawFrame2, canvas);
    context.clearRect(0, 0, canvasWidth, canvasHeight);
    balls2.forEach(draw);
    }());
};	

Example 3. Screenwrapping

Your browser does not support Canvas. Update your browser to the latest version.

Use the following keystrokes to control the 'spaceship':

  • Counterclockwise rotation
  • Clockwise rotation
  •   Acceleration

HTML

  <!doctype html>
  <html>
  <head>
  <title>Screenwrapping</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="js/service.js"></script>
  <script src="js/spaceship.js"></script>
  <script src="js/functions.js"></script>
  <script>
      $(document).ready(function() {
        screenWrapping();
      });
  </script>
  </head>
  <body> 
  <canvas id="screen_wrapping" style="border: 1px solid;" >
  Verwijderen van een bewegend voorwerp op het Canvas.
  </canvas>
  </body>
  </html>

Javascript code in spaceship.js

// JavaScript Document

function Ship () {
  this.x = 0;
  this.y = 0;
  this.width = 25;
  this.height = 20;
  this.rotation = 0;
  this.showFlame = false;
  }
  
  Ship.prototype.draw = function (context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.rotation);
  
  context.lineWidth = 1;
  context.strokeStyle = "#000000";
  context.beginPath();
  context.moveTo(10, 0);
  context.lineTo(-10, 10);
  context.lineTo(-5, 0);
  context.lineTo(-10, -10);
  context.lineTo(10, 0);
  context.stroke();
  if (this.showFlame) {
      context.beginPath();
      context.strokeStyle = "#000000";
      context.moveTo(-7.5, -5);
      context.lineTo(-15, 0);
      context.lineTo(-7.5, 5);
      context.stroke();
  }
  context.restore();
};

Javascript

 function screenWrapping(){
	
	      var canvas = jQuery('#screen_wrapping');
		  var context = canvas.get(0).getContext('2d');
		  var parentWidth=jQuery(canvas).parent().width();
		  var canvasWidth=context.canvas.width = parentWidth;
		  var canvasHeight=context.canvas.height = 288;
          var ship = new Ship();
          var vr = 0;
          var vx = 0;
          var vy = 0;
          var thrust = 0;
         
		 ship.x = canvasWidth / 2;
         ship.y = canvasHeight / 2;

      window.addEventListener('keydown', function (event) {
        switch (event.keyCode) {
        case 37:      //left
          vr = -3;
          break;
        case 39:      //right
          vr = 3;
          break;
        case 38:      //up
          thrust = 0.20;
          ship.showFlame = true;
          break;
        }
      }, false);

      window.addEventListener('keyup', function () {
        vr = 0;
        thrust = 0;
        ship.showFlame = false;
      }, false);

      (function drawFrame3 () {
        window.requestAnimationFrame(drawFrame3, canvas);
        context.clearRect(0, 0, canvasWidth, canvasHeight);

        ship.rotation += vr * Math.PI / 180;
        var angle = ship.rotation, //in radians
            ax = Math.cos(angle) * thrust,
            ay = Math.sin(angle) * thrust,
            left = 0,
            right = canvasWidth,
            top = 0,
            bottom = canvasHeight;

        vx += ax;
        vy += ay;
        ship.x += vx;
        ship.y += vy;
        
        //screen wrapping
        if (ship.x - ship.width / 2 > right) {
          ship.x = left - ship.width / 2;
        } else if (ship.x + ship.width / 2 < left) {
          ship.x = right + ship.width / 2;
        }
        if (ship.y - ship.height / 2 > bottom) {
          ship.y = top - ship.height / 2;
        } else if (ship.y < top - ship.height / 2) {
          ship.y = bottom + ship.height / 2;
        }
        ship.draw(context);
      }());
    }; 

Next tutorial

Leave a comment