Essay - Published: 2025.03.05 | build | create | creative-coding | javascript | p5js |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
I built a sketch that animates a sine wave in p5.js. Here I'll walk through how it's built.
2025-02_sine-wave - a p5.js sketch animating a sine wave from right to left.
On each render frame:
Variables:
You can also play with it live on Open Processing - 2025-02_sine-wave
let phase = 0;
const frequency = 0.2;
const color_black = "#000000"
const color_white = "#ffffff"
const color_red = "#BC1E22"
const bg_color = color_black
const fg_color = color_white
const width = 500
const height = 1000
const amplitude = 200;
function setup() {
createCanvas(width, height);
}
function draw() {
background(bg_color);
stroke(fg_color);
strokeWeight(2);
noFill();
beginShape();
for (let x = 0; x < width; x++) {
// Variable amplitude - larger in the middle, smaller on the sides
const distFromCenter = 1 - Math.abs((x - width/2) / (width/2));
const variableAmplitude = amplitude * (0.1 + 0.9 * distFromCenter * distFromCenter);
// Calculate y position for each point along the sine wave
const y = height/2 + variableAmplitude * sin(frequency * x + phase);
vertex(x, y);
}
endShape();
// Increase phase to animate the wave
phase += 0.02;
}
I haven't played around with creative coding in awhile but recently have gotten back into it. I'm particularly interested in how the new era of vibe coding can lower the barrier to entry to building whatever you can imagine - this sketch was built 90% by Claude 3.5 before I came in to adjust variables / parts of it to fit my vision.
If you liked this post you might also like:
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.