Better sparkle

by Nick

HTML

<head>

</head>
<body>
  <section>
    <canvas id="canvas"></canvas>
  </section>
  
  <button id="start">Start Animation</button>
  <button id="stop">Stop Animation</button>
</body>

CSS

* {
  margin: 0;
  padding: 0;
}

html {
  background-color: rgb(45, 48, 59);
}

section {
  width: 100%;
  height: 300px;
  background-color: rgb(190, 213, 223);
}

JavaScript

var canvas = document.getElementById("canvas");
var draw = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.style.width = window.innerWidth;
canvas.height = 300;
canvas.style.height = 300;

// General config settings.
var config = {
  maxSparkles: 10,
	maxRadius: 30,
  minRadius: 15,
  increment: 0.3,
  maxDelay: 4000 // in milliseconds
}

// The sparkles array will fill up to config.maxSparkles
var sparkles = [];
var animControl;

// This just adds an event listener to the "Start Animation" button on the page.
document.getElementById("start").addEventListener("click", function() {
  console.log("Animation started!");
  animControl = window.requestAnimationFrame(animate);
});

// This adds an event listener to the "Stop Animation" button on the page.
document.getElementById("stop").addEventListener("click", function() {
  console.log("Animation stopped.");
  window.cancelAnimationFrame(animControl);
});

// Handles the animation of the sparkles.
function animate(timestamp)
{
  // Observe the timestamp gives by requestAnimationFrame in console.
  // console.log(timestamp);

  // Clears the previous frame;
  draw.clearRect(0, 0, canvas.width, canvas.height);

  // Loop through each index of sparkles. Doing this lets us draw multiple
  // sparkles at once.
  for (i = 0; i < sparkles.length; i++)
  {
    if (sparkles[i] != null)
    {
      // If the sparkle's delay is not set, then set it.
      // This is necessary to do here since the timestamp that requestAnimationFrame
      // puts in as a parameter is always growing.
      if (sparkles[i].delay == null)
      {
        sparkles[i].delay = Math.floor(Math.random()*config.maxDelay) + timestamp;
      }

      // Handles whether to animate the next frame or to remove this sparkle from array.
      // If timestamp is larger than sparkle's delay, this means it's time to
      // animate this sparkle.
      if (timestamp > sparkles[i].delay)
      {
        // Increment the input variable and...