drawFall

by trentHarlem

HTML

<canvas id="canvas"></canvas>

CSS

body {
  margin: 0;
}

canvas {
  background-color: black;
  cursor: pointer;
}

JavaScript

const canvas = document.getElementById('canvas')
// get the context
const c = canvas.getContext('2d')
// set the width and height of the canvas
canvas.width = window.innerWidth
canvas.height = window.innerHeight

const circleArray = []
// let color = 'dodgerblue'
let opacity = 1
let color = `rgb(30, 144, 255, ${opacity})`


class Circle {
  constructor(x, y, r, o, c) {
    this.x = x
    this.y = y
    this.radius = r
    this.opacity = o
    this.color = c
  }

  draw() {
    //  color with new opacity value
    this.color = `rgb(30, 144, 255, ${this.opacity})`
    c.beginPath()
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
    // create color gradient
    let gradient = c.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.radius)
    gradient.addColorStop(0, this.color)
    gradient.addColorStop(1, 'transparent')
    c.fillStyle = gradient
    // c.fillStyle = this.color
    c.fill()
  }

  update() {
    //  check if particle is still within canvas
    if (this.y < canvas.height) {
      // update the particle radius
      if (this.radius > 0) this.radius -= 0.5
      //  update the path
      this.y += 2
      // update opacity value
      this.opacity = (1 - this.y / canvas.height).toFixed(2)
      //  draw the updated particle
      this.draw()
    }
  }
}

//  add event listener to detect mouse move
window.addEventListener('mousemove', function(event) {
  //  get the mouse position
  let mouse_x = event.x
  let mouse_y = event.y
  // add circle at mouse position
  circleArray.push(new Circle(mouse_x, mouse_y, 69.00, opacity, color))
})

// add event listener to detect window resize
window.addEventListener('resize', function() {
  // set the width and height of the canvas
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
})

function animate() {
  requestAnimationFrame(animate)
  c.clearRect(0, 0, innerWidth, innerHeight)
  circleArray.filter(c => c.y > canvas.height).forEach((c, i) => circleArray.splice(i,...