Explosion Animation in Canvas


In this tutorial, we will learn to create an explosion animation effect using canvas in HTML. Using canvas, we can draw graphics on a web page in an easy and powerful way.

Let’s see some examples of creating explosion animation in canvas.

Explosion Animation 1

We will create an explosion of 50 randomly colored particles that originate from the center of the canvas and move in random directions. The particles will continue to move until the page is refreshed.

Algorithm

  • Step 1 − Create an HTML canvas element with an id of "explosion" and set its dimensions to 400x400 pixels.

  • Step 2 − Initialize a particle array to store particle objects and a 2D rendering context for the canvas element.

  • Step 3 − Define a function createExplosion( ) that pushes 50 particle objects to the particle array. Each particle object has properties for the x and y position, radius, color, horizontal velocity, and vertical velocity. The x and y positions and the color are set to random values, and the radius and velocities are set to random numbers within a specific range.

  • Step 4 − Define a function draw( ) that clears the canvas and iterates through the particle array, drawing a circle for each particle using its properties.

  • Step 5 − Define a function update( ) that iterates through the particle array and updates each particle's x and y position based on its velocity.

  • Step 6 − Define a function animate() that calls the update( ) and draw( ) functions and then calls itself using requestAnimationFrame.

  • Step 7 − Call the createExplosion() function to initialize the particle array.

  • Step 8 − Call the animate() function to start the animation.

Example

In the below example, we are creating the illusion of movement. We change the particle’s properties and draw and update it continuously on the canvas using an animation loop.

<html>
<head>
   <style>
      canvas {
         border: 2px solid black;
      }
   </style>
</head>
<body>
   <canvas id="explosion" width="550" height="400"></canvas>
   <script>
      const canvas = document.getElementById('explosion');
      const context = canvas.getContext('2d');
      let particles = [];
      
      // Creates a new particle at the center of the canvas
      function createExplosion() {
         for (let i = 0; i < 50; i++) {
            particles.push({
               x: canvas.width / 2,
               y: canvas.height / 2,
               radius: Math.random() * 3 + 1,
               color: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`,
               velocityX: Math.random() * 20 - 10,
               velocityY: Math.random() * 20 - 10
            });
         }
      }
      
      // Renders the particles onto the canvas
      function draw() {
         context.clearRect(0, 0, canvas.width, canvas.height);
         particles.forEach(particle => {
            context.beginPath();
            context.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
            context.fillStyle = particle.color;
            context.fill();
            context.closePath();
         });
      }
      
      // Updates the positions of the particles
      function update() {
         particles.forEach(particle => {
            particle.x += particle.velocityX;
            particle.y += particle.velocityY;
         });
      }
      // The main animation loop
      function animate() {
         update();
         draw();
         requestAnimationFrame(animate);
      }
      createExplosion();
      animate();
   </script>
</body>
</html>

Explosion Animation 2

We will use event listeners and will detect mouse movement. When a mousemove event is detected, we will update the mouse object's x and y positions and push five new particle objects to the array. So, it will look like an explosion.

Algorithm

  • Step 1 − Initialize the following variables −

    • canvas − the canvas element with id "mCanvas"

    • ctx − the 2D rendering context for the canvas

    • particlesArray − an empty array to store particle objects

    • hue − a variable initialized to 0

  • Step 2 − Set the height and width of the canvas element to the inner height and width of the window, respectively.

  • Step 3 − Add a resize event listener to the window object to update the height and width of the canvas element whenever the window is resized.

  • Step 4 − Initialize a mouse object with properties x and y both set to undefined.

  • Step 5 − Define a Particles class with the following methods:

  • Step 5.1constructor() sets the following properties for each particle object −

    • x − the current x position of the mouse object

    • y − the current y position of the mouse object

    • size − a random number between 1 and 10

    • speedX − a random number between -1.5 and 1.5

    • speedY −a random number between -1.5 and 1.5

  • Step 5.2 − update(); this method increments the x and y position of the particle by its speedX and speedY values, respectively. If the particle's size is greater than .3, decrement it by .1.

  • Step 5.3 − draw(); this method sets the fill style of the ctx object to a color in the hue-saturation-lightness (HSL) color space using the hue value and fills a circular path with the particle's x and y position as the center and its size as the radius.

  • Step 6 − Define a handleParticles() function to iterate through the particlesArray. For each particle in the array, call its update and draw methods. If a particle's size becomes less than or equal to .3, remove it from the array.

  • Step 7 − Define an animate() function to fill the canvas element with a semi-transparent black rectangle, handle the particles in the particlesArray, and increment the hue value.

  • Step 8 − Call the animate() function using requestAnimationFrame.

  • Step 9 − Add a mousemove event listener to the canvas element. When a mousemove event is detected, update the x and y properties of the mouse object and push five new particle objects to the particlesArray.

Example

In the below example, we will create an explosion animation which will be performed whenever there is a movement of the mouse. We can achieve this using an event listener.

<html>
<head>
   <style>
      body {
         padding: 0;
         margin: 0;
         box-sizing: border-box;
         background: #000;
      }
      #mCanvas{
         height: 100%;
         width: 100%;
         position: absolute;
         top: 0;
         left: 0;
         background: #000;
      }
   </style>
</head>
<body>
   <canvas id="mCanvas"></canvas>
   <script>
      const canvas = document.getElementById('mCanvas');
      const ctx = canvas.getContext('2d');
      const particlesArray = [];
      let hue = 0;
      canvas.height = window.innerHeight;
      canvas.width = window.innerWidth;
      window.addEventListener('resize', function(){
         canvas.height = window.innerHeight;
         canvas.width = window.innerWidth;
      })
      const mouse = {
         x: undefined,
         y: undefined
      }
      class Particles{
         constructor(){
            this.x = mouse.x;
            this.y = mouse.y;
            this.size = Math.random()*10 + 1;
            this.speedX = Math.random()*3 - 1.5;
            this.speedY = Math.random()*3 - 1.5;
         }
         update(){
            this.x += this.speedX;
            this.y += this.speedY;
            if(this.size > .3){
               this.size -= .1;
            }
         }
         draw(){
            ctx.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
         }
      } // end Particle
      function handleParticles(){
         for(let i=0 ; i<particlesArray.length ; i++){
            particlesArray[i].update();
            particlesArray[i].draw();
            if(particlesArray[i].size <= .3){
               particlesArray.splice(i, 1);
               i--;
            }
         }
      } // end of function
      function animate(){
         ctx.fillStyle = 'rgba(0,0,0, .1)';
         ctx.fillRect(0, 0, canvas.width, canvas.height);
         handleParticles();
         hue++;
         requestAnimationFrame(animate);
      }
      animate();
      canvas.addEventListener('mousemove', function(event){
         mouse.x = event.x;
         mouse.y = event.y;
         for(let i=0 ; i<5 ; i++){
            particlesArray.push(new Particles());
         }
      })
   </script>
</body>
</html>

We have created an explosion effect with a canvas element. When the mouse is moved over the canvas, the page creates new particle objects and adds them to an array. The particles have random positions, sizes, and speeds and are drawn on the canvas using a hue value that changes over time. The particles shrink as they move and are removed from the array when their size becomes small enough. The canvas is continually redrawn using the requestAnimationFrame function to create an animation effect. The page also updates the dimensions of the canvas element whenever the window is resized.

We have learned to create different explosion animation effects in canvas.

Updated on: 17-Mar-2023

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements