HomeCanvasFireworks On Click | Javascript & Canvas

Fireworks On Click | Javascript & Canvas

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to create fireworks on mouse click. To do this project, we need HTML Canvas and Javascript. It is an intermediate-level project. You need a basic knowledge of canvas & intermediate knowledge of Javascript to build this project.
 
If you are looking for more such tutorials to improve your frontend skills, check out this playlist here. This playlist consists of 100+ projects built using HTML, CSS and Javascript. Also, each of these projects comes along with a free-to-download source code.
 

Video Tutorial:

If you prefer watching a video tutorial rather than reading this blog post, you can check out the video down below. Also, subscribe to my youtube channel where I post new tutorials every alternate day.

Project Folder Structure:

Before we start to code let us take a look at the project folder structure. We create a project folder called – ‘Fireworks On Click’. Within this folder, we have three files. These files are index.html, style.css and script.js. The first file is the HTML document, the next is the stylesheet and the last file is the script file.

HTML:

We begin with the HTML code. The HTML code consists of a div with the class name ‘container’. Inside the container, we have a canvas element with a unique id – ‘canvas’.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fireworks On Click</title>
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <canvas id="canvas">Canvas is not supported in your browser!</canvas>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we do a basic CSS reset and add background colour to the canvas using CSS. For this copy, the code provided to you below and paste it into the stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  overflow: hidden;
}
canvas {
  background-color: #000000;
}

Javascript:

Next, we add functionality to this code using Javascript. Now copy the code below and paste it into your script file.

We implement the logic in the following steps:

  1. Create Initial References & declare variables
  2. Create events object
  3. Request animation frame on all browsers
  4. Function on window load
  5. Detect Touch Device
  6. Function on mouse down
  7. Function on mouse down
  8. A Function to generate a random number between a given range
  9. Function to generate particle
  10. Function to create fireworks
  11. Create a function to begin the fireworks.
//Create Initial References & declare variables
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let width = window.innerWidth;
let height = window.innerHeight;
let clicked = false;
let mouseX = 0,
  mouseY = 0;
let particles = [];
let particleSettings = {
  gravity: 0.05,
};

//Events Object
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//For using request animationFrame on all browsers
window.requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function (callback) {
    window.setTimeout(callback, 1000 / 60);
  };

//Function on window load
window.onload = () => {
  canvas.width = width;
  canvas.height = height;
  window.requestAnimationFrame(startFireWork);
};

//Detect Touch Device
const isTouchDevice = () => {
  try {
    //We try to create TouchEvent (it fails for desktops and throws error)
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

isTouchDevice();

//Function on mousedown
canvas.addEventListener(events[deviceType].down, function (e) {
  e.preventDefault();
  clicked = true;
  mouseX = isTouchDevice() ? e.touches[0].pageX : e.pageX;
  mouseY = isTouchDevice() ? e.touches[0].pageY : e.pageY;
});

//Function on mouseup
canvas.addEventListener(events[deviceType].up, function (e) {
  e.preventDefault();
  clicked = false;
});

//Function to generate random number between a given range
function randomNumberGenerator(min, max) {
  return Math.random() * (max - min) + min;
}

function Particle() {
  this.width = randomNumberGenerator(0.1, 0.9) * 5;
  this.height = randomNumberGenerator(0.1, 0.9) * 5;
  this.x = mouseX - this.width / 2;
  this.y = mouseY - this.height / 2;

  //Velocity of the particle
  this.vx = (Math.random() - 0.5) * 10;
  this.vy = (Math.random() - 0.5) * 10;
}

Particle.prototype = {
  move: function () {
    if (this.x >= canvas.width || this.y >= canvas.height) {
      return false;
    }
    return true;
  },
  draw: function () {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += particleSettings.gravity;
    context.save();
    context.beginPath();
    context.translate(this.x, this.y);
    context.arc(0, 0, this.width, 0, Math.PI * 2);
    context.fillStyle = this.color;
    context.closePath();
    context.fill();
    context.restore();
  },
};

function createFirework() {
  //Increase range for bigger fireworks
  var numberOfParticles = randomNumberGenerator(10, 50);
  let color = `rgb(${randomNumberGenerator(0, 255)},${randomNumberGenerator(
    0,
    255
  )},${randomNumberGenerator(0, 255)})`;

  for (var i = 0; i < numberOfParticles; i++) {
    var particle = new Particle();
    particle.color = color;
    var vy = Math.sqrt(25 - particle.vx * particle.vx);
    if (Math.abs(particle.vy) > vy) {
      particle.vy = particle.vy > 0 ? vy : -vy;
    }
    particles.push(particle);
  }
}

//Function that begins the firework
function startFireWork() {
  let current = [];
  //Control trail left by particles throught the value of alpha
  context.fillStyle = "rgba(0,0,0,0.1)";
  context.fillRect(0, 0, width, height);
  if (clicked) {
    createFirework();
  }
  for (let i in particles) {
    particles[i].draw();
    if (particles[i].move()) {
      current.push(particles[i]);
    }
  }
  particles = current;
  window.requestAnimationFrame(startFireWork);
}

That’s all for this tutorial. If you face any issues while creating this code you can download the source code by clicking on the ‘Download Code’ button below. Also, If you have any queries, suggestions or feedback you can comment below.

Previous articleQuiz #6
Next articlePineapple Animation CSS
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

seventeen + five =

Most Popular