Animating Sine Waves with p5.js
Date: 2025-03-05 | build | create | creative-coding | javascript | p5js |
I built a sketch that animates a sine wave in p5.js. Here I'll walk through how it's built.
What is it?
2025-02_sine-wave - a p5.js sketch animating a sine wave from right to left.
How it's built
On each render frame:
- Create a shape to represent the line and render it
- For each x coordinate:
- Calculate the y coordinate by finding the distance from center percentage, scaling that to 10% to ~200% of the amplitude, then placing it by multipying against the current since wave value
- Increment phase so the next render shows the sine wave moved a small amount
Variables:
- Phase - The current "position" of the sine wave
- Frequency - How frequently we see curves
- Amplitude - How high the curves are
Full source code
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;
}
Next
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:
Want more like this?
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.