Skip to contentCREATIVE·CODE·ART
16
1.4
5
1
p5.js

Harp Field

Sixteen strings, tuned to light. Run a finger across them and they ring — the faster you sweep, the brighter they burn. Idle, it plays itself, one slow note at a time.

Licence: CC BY-NC-SA 4.0: remix with credit, non-commercial, share alike

View the code
// Harp Field — a p5.js instrument you play by touch
// A row of strings. Drag across them to pluck; idle, the field plays a slow
// arpeggio by itself. Palette: charcoal, bone, signal orange.
// Site sliders: Strings · Tension · Glow · Wave — read through params.*

const BG = [13, 13, 18];
const BONE = [233, 229, 218];
const ORANGE = [255, 180, 84];

let strings = [];
let lastPluck = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(...BG);
}

function layout() {
  const n = round(params.strings ?? 16);
  if (strings.length !== n) {
    strings = [];
    for (let i = 0; i < n; i++) {
      strings.push({ y: ((i + 1) / (n + 1)) * height, amp: 0, phase: random(TWO_PI) });
    }
  } else {
    for (let i = 0; i < n; i++) strings[i].y = ((i + 1) / (n + 1)) * height;
  }
}

function draw() {
  background(...BG);
  layout();

  const tension = params.tension ?? 1.4;
  const wave = params.wave ?? 1;
  const glow = params.glow ?? 5;

  if (mouseIsPressed || (mouseX > 0 && mouseY > 0)) {
    for (const s of strings) {
      if (abs(mouseY - s.y) < 14 && abs(mouseX - width / 2) < width * 0.46) {
        const v = constrain(abs(mouseY - pmouseY) * 0.35 + 2.2, 2.2, 13);
        if (v > s.amp) { s.amp = v; s.phase = 0; }
      }
    }
  }
  if (frameCount - lastPluck > 54 && strings.length) {
    const s = random(strings);
    if (s.amp < 2.4) { s.amp = random(5, 8.5); s.phase = 0; }
    lastPluck = frameCount;
  }

  const SEG = 56;
  for (const s of strings) {
    s.phase += 0.16 * wave;
    s.amp *= pow(0.992, tension);
    if (s.amp < 0.02) s.amp = 0;
    const heat = constrain(s.amp / 12, 0, 1);
    const cr = lerp(BONE[0], ORANGE[0], heat);
    const cg = lerp(BONE[1], ORANGE[1], heat);
    const cb = lerp(BONE[2], ORANGE[2], heat);
    for (const [alpha, wgt] of [[36, 1 + glow * heat], [215, 1.3]]) {
      stroke(cr, cg, cb, alpha);
      strokeWeight(wgt);
      noFill();
      beginShape();
      for (let i = 0; i <= SEG; i++) {
        const x = (i / SEG) * width;
        const fr = i / SEG;
        const env = sin(fr * PI);
        const y = s.y + sin(s.phase + fr * PI * 2) * s.amp * env * 3.2
                      + sin(s.phase * 2.03 + fr * PI * 4) * s.amp * env * 0.85;
        vertex(x, y);
      }
      endShape();
    }
    noStroke();
    fill(cr, cg, cb, 200);
    ellipse(6, s.y, 4); ellipse(width - 6, s.y, 4);
  }
}

function keyPressed() {
  if (key === 's' || key === 'S') saveCanvas('harp-field', 'png');
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
  strings = [];
}