The concept
Stereoscopy exploits binocular parallax: left and right eyes see slightly offset images, the brain interprets the offset as depth. In VR, two cameras are rendered with an interocular distance (~6.4cm). In p5.js, we simulate depth through atmospheric blur, scale, and mouse parallax.
The code
// Depth: parallax layers simulating 3D depth
let layers = [];
function setup() {
createCanvas(400, 280);
for (let i = 0; i < 5; i++) {
layers.push({z:i, objects:[]});
for (let j = 0; j < 4+i*2; j++) {
layers[i].objects.push({x:random(width),y:random(height)});
}
}
}
function draw() {
background(11, 15, 20);
let mx = (mouseX - width/2) / width;
for (let l of layers) {
let parallax = mx * (l.z+1) * 15;
let alpha = map(l.z, 0, 4, 40, 220);
let sz = map(l.z, 0, 4, 4, 16);
noStroke(); fill(55,227,195,alpha);
for (let o of l.objects)
ellipse(o.x + parallax, o.y, sz, sz);
}
}Going further
Explore other free courses on the Workshops page.
Practice, collaborate, deploy — in 15 min.
Book a discovery call →