RAGINGNEXUS

particles · 07 · 2020

Particle Effects

  • p5.js, particles
  • JavaScript code running in a web browser
  • 4 controls · source on this page
  • 5 renders

Source — sketch.js

'use strict'

class Particle {
  constructor(sketch, circle_color, line_color, min_radius = 5, max_radius = 15) {
    this.sketch = sketch

    this.max_speed = 2

    this.circle_color = circle_color || "#999999"
    this.line_color = line_color || "gray"

    this.min_radius = min_radius
    this.max_radius = max_radius

    this.reset()
  }

  reset() {
    this.radius   = this.sketch.random(this.min_radius, this.max_radius)
    this.position = this.sketch.createVector(this.sketch.random(this.sketch.width),this.sketch.random(this.sketch.height))
    this.velocity = this.sketch.createVector(this.sketch.random(this.max_speed * -1, this.max_speed),this.sketch.random(this.max_speed * -1, this.max_speed))
  }

  update() {
    this.position.add(this.velocity)
    this.edges()
  }

  // Bounce at the edges. The position is pulled back inside as well as the
  // direction flipped, or a particle left outside by the canvas shrinking
  // (a resize, leaving fullscreen) would flip every frame and stay stuck.
  edges() {
    let { width, height } = this.sketch
    if (this.position.x <= 0 || this.position.x >= width) {
      this.velocity.x = Math.abs(this.velocity.x) * (this.position.x <= 0 ? 1 : -1)
      this.position.x = Math.min(Math.max(this.position.x, 0), width)
    }
    if (this.position.y <= 0 || this.position.y >= height) {
      this.velocity.y = Math.abs(this.velocity.y) * (this.position.y <= 0 ? 1 : -1)
      this.position.y = Math.min(Math.max(this.position.y, 0), height)
    }
  }

  draw() {
    this.sketch.push()

    this.sketch.fill(this.circle_color)
    this.sketch.stroke(this.circle_color)

    this.sketch.circle(this.position.x, this.position.y, this.radius)

    this.sketch.pop()
  }

  // A line to every particle from `start` on that's closer than
  // maximum_distance, fading out as the distance grows, so links appear and
  // disappear smoothly instead of blinking on and off at the limit. Squared
  // distances are compared first, so the square root is only worked out
  // for pairs that are actually linked.
  drawLinkToNearParticles(particles, start, maximum_distance) {
    let context = this.sketch.drawingContext
    let limit = maximum_distance * maximum_distance
    let { x, y } = this.position
    this.sketch.push()
    this.sketch.stroke(this.line_color)
    for (let i = start; i < particles.length; i++) {
      let other = particles[i].position
      let dx = other.x - x, dy = other.y - y
      let squared = dx * dx + dy * dy
      if (squared < limit) {
        context.globalAlpha = 1 - Math.sqrt(squared) / maximum_distance
        this.sketch.line(x, y, other.x, other.y)
      }
    }
    this.sketch.pop()
    context.globalAlpha = 1
  }
}

// Avoiding Global Mode: https://github.com/processing/p5.js/wiki/Global-and-instance-mode
const experiment = ( sketch ) => {
  //
  // Configuration
  //
  let container = document.getElementById('sketch-holder')
  let canvas_el

  let maximum_distance = 100
  let number_of_particles = Math.floor(container.clientWidth / 10)
  let particles = []

  // The same seed gives the same particles, in the same places, going the same way
  let seed = Math.floor(Math.random() * 1000000)

  // One entry per slider: its [min, max, step], where its value lives and
  // what a new value does. Each one is wired to the elements named after it,
  // "maximum_distance" to #experiment-control-maximum-distance and its label
  // #experiment-label-maximum-distance
  let sliders = {
    particle_count:   { range: [10, 500, 1], value: () => number_of_particles, update: value => { updateParticleCount(value) } },
    maximum_distance: { range: [10, 500, 1], value: () => maximum_distance,    update: value => { maximum_distance = value } }
  }

  // Color Schemes
  //
  // Each particle picks its circle and line colours at random from the
  // scheme's lists. The two "site" schemes use the site's own palette.
  let color_scheme
  let color_sets = {
    site_dark: {
      background: "#0a0a0a",
      label: "Site Dark",
      circle: ["#ff6600", "#f5f5f5", "#f5f5f5"],
      line: ["#ff6600", "#8a8a8a", "#8a8a8a"],
      min_radius: 3,
      max_radius: 8
    },
    site_light: {
      background: "#ffffff",
      label: "Site Light",
      circle: ["#b84900", "#0a0a0a", "#0a0a0a"],
      line: ["#ff9a52", "#9a9a9a", "#9a9a9a"],
      min_radius: 3,
      max_radius: 8
    },
    black_white: {
      background: "black",
      label: "Light on black",
      circle: ['rgb(240, 240, 240)'],
      line: ['rgb(200, 200, 200)'],
      min_radius: 1,
      max_radius: 5
    },
    white_black: {
      background: "white",
      label: "Dark on white",
      circle: ['rgb(40, 40, 40)'],
      line: ['rgba(100, 100, 100, 0.8)'],
      min_radius: 5,
      max_radius: 10
    },
    black_color: {
      background: "black",
      label: "Colourful on black",
      circle: ['#04E762', '#F5B700', '#00A1E4', '#DC0073', '#89FC00'],
      line: ['#04E76288', '#F5B70088', '#00A1E488', '#DC007388', '#89FC0088'],
      min_radius: 5,
      max_radius: 10
    },
    red_white: {
      background: "red",
      label: "Large white circles on red",
      circle: ["white"],
      line: ["white"],
      min_radius: 10,
      max_radius: 30
    }
  }

  // Controls
  let controls = {
    color_scheme_picker: document.getElementById("experiment-control-color-scheme"),
    seed: document.getElementById("experiment-control-seed"),
    new_seed: document.getElementById("experiment-control-new-seed"),
    play_pause_toggle: document.getElementById("experiment-control-pause-toggle"),
    restart: document.getElementById("experiment-control-restart"),
    save: document.getElementById("experiment-control-save"),
    fullscreen: document.getElementById("experiment-control-fullscreen-toggle")
  }

  Object.keys(sliders).forEach(name => {
    let id = name.replaceAll('_', '-')
    sliders[name].control = document.getElementById(`experiment-control-${id}`)
    sliders[name].label = document.getElementById(`experiment-label-${id}`)
  })

  //
  // Control Handling
  //

  function setupControls() {
    Object.values(sliders).forEach(slider => {
      [slider.control.min, slider.control.max, slider.control.step] = slider.range
      slider.control.value = slider.value()
      slider.label.textContent = slider.value()
    })

    Object.entries(color_sets).forEach(([key, scheme]) => {
      controls.color_scheme_picker.add(new Option(scheme.label, key, false, key === color_scheme))
    })

    controls.seed.value = seed

    updatePlayPauseIcon()
    updateFullscreenIcon()
  }

  // Both toggle buttons hold two icons and show the one for what a click
  // will do next, read from the actual state rather than from counting
  // clicks, so leaving fullscreen with the Escape key keeps the icon right.
  function showIcon(button, name) {
    button.querySelectorAll('svg').forEach(icon => {
      icon.classList.toggle('hidden', !icon.classList.contains(`icon-${name}`))
    })
  }

  function updatePlayPauseIcon() {
    showIcon(controls.play_pause_toggle, sketch.isLooping() ? 'pause' : 'play')
  }

  function updateFullscreenIcon() {
    showIcon(controls.fullscreen, document.fullscreenElement ? 'compress' : 'expand')
  }

  // While paused nothing redraws by itself, so any change has to ask for it
  function refresh() {
    if (!sketch.isLooping()) sketch.redraw()
  }

  function installControlHandlers() {
    controls.play_pause_toggle.addEventListener("click", () => {
      sketch.isLooping() ? sketch.noLoop() : sketch.loop()
      updatePlayPauseIcon()
    })

    controls.restart.addEventListener("click", restart)

    // A new scheme recolours the particles already there rather than
    // starting over
    controls.color_scheme_picker.addEventListener("change", event => {
      color_scheme = event.target.value
      let scheme = color_sets[color_scheme]
      particles.forEach(particle => {
        particle.circle_color = sketch.random(scheme.circle)
        particle.line_color   = sketch.random(scheme.line)
        particle.radius       = sketch.random(scheme.min_radius, scheme.max_radius)
      })
      refresh()
    })

    Object.values(sliders).forEach(slider => {
      slider.control.addEventListener("input", event => {
        slider.label.textContent = event.target.value
        slider.update(parseInt(event.target.value))
        refresh()
      })
    })

    // Seed. Typing one in brings those particles back, the button rolls new ones
    controls.seed.addEventListener("change", event => {
      seed = parseInt(event.target.value) || 0
      controls.seed.value = seed
      restart()
    })

    controls.new_seed.addEventListener("click", () => {
      seed = Math.floor(Math.random() * 1000000)
      controls.seed.value = seed
      restart()
    })

    controls.save.addEventListener("click", () => {
      sketch.save(canvas_el, `particle_effects_${color_scheme}_seed${seed}_${number_of_particles}_${maximum_distance}_${Math.floor(Date.now() / 1000)}`, 'png')
    })

    controls.fullscreen.addEventListener("click", () => {
      sketch.fullscreen(!document.fullscreenElement)
    })

    // p5's fullscreen() puts <html> in fullscreen, not #sketch-holder, and the
    // resize event doesn't reliably wait for the CSS transition that grows
    // the holder, so resize once the change has actually settled.
    document.addEventListener('fullscreenchange', () => {
      updateFullscreenIcon()
      sketch.windowResized()
    })
  }

  //
  // P5.js touchpoints
  //
  sketch.setup = () => {
    canvas_el = sketch.createCanvas(container.clientWidth, container.clientHeight)
    canvas_el.parent(container)

    // Start on the scheme that matches the theme the site is being read in
    color_scheme = document.documentElement.classList.contains('dark') ? 'site_dark' : 'site_light'

    // It moves by itself, unless the reader has asked their system for
    // less motion
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) sketch.noLoop()

    setupControls()
    installControlHandlers()
    resetParticles()
  }

  sketch.windowResized = () => {
    sketch.resizeCanvas(container.clientWidth, container.clientHeight)
    refresh()
  }

  sketch.draw = () => {
    sketch.background(color_sets[color_scheme].background)

    // Each pair is linked once: a particle only looks at the ones after it
    particles.forEach((particle, index) => {
      particle.drawLinkToNearParticles(particles, index + 1, maximum_distance)
    })
    particles.forEach(particle => particle.draw())

    // Movement only happens while playing, so a redraw asked for by a
    // control while paused shows the same moment
    if (sketch.isLooping()) particles.forEach(particle => particle.update())
  }

  //
  // Helper methods
  //

  function buildParticle() {
    let scheme = color_sets[color_scheme]
    return new Particle(
      sketch,
      sketch.random(scheme.circle),
      sketch.random(scheme.line),
      scheme.min_radius,
      scheme.max_radius
    )
  }

  // Adds or removes particles to match the count, keeping the ones already there
  function updateParticleCount(value) {
    number_of_particles = value

    if (number_of_particles < particles.length) {
      particles.splice(number_of_particles)
    } else {
      for (let i = particles.length; i < number_of_particles; i++) {
        particles[i] = buildParticle()
      }
    }
  }

  // A fresh set of particles from the current seed
  function resetParticles() {
    sketch.randomSeed(seed)
    particles = []
    updateParticleCount(number_of_particles)
  }

  function restart() {
    resetParticles()
    refresh()
  }
}

// Wait for everything to load
if (document.readyState === 'complete') {
  new p5(experiment)
} else {
  window.addEventListener('load', () => new p5(experiment))
}