Menger Sponge Fractal style body background color rgb 200 200 200 min height 600px canvas margin auto style script src https cdnjs cloudflare com ajax libs p5 js 0 7 1 p5 min js script script let a 0 let b let sponge new Array const recursiveLimit 4 let recursiveCount 0 let clickSe function setup createCanvas 600 600 WEBGL ambientLight 100 directionalLight 120 120 120 1 1 1 ambientMaterial 230 210 255 255 noStroke resetCube function mousePressed recursiveCount if recursiveCount recursiveLimit resetCube return let next new Array sponge forEach abox let newBoxes abox generate next concat next newBoxes sponge next function draw camera 0 0 500 0 0 0 0 1 0 background 30 30 60 rotateX a rotateY a 0 4 rotateZ a 0 1 sponge forEach abox abox show a 0 01 function resetCube b new Box 0 0 0 300 sponge b recursiveCount 0 class Box constructor x y z r_ this pos createVector x y z this r r_ generate let boxes new Array for let x 1 x 2 x for let y 1 y 2 y for let z 1 z 2 z let sum abs x abs y abs z const newR this r 3 if sum 1 let b new Box this pos x x newR this pos y y newR this pos z z newR newR boxes push b return boxes show push translate this pos x this pos y this pos z box this r pop console log click cube to do the Menger Sponge Fractal console log ready script
rEach abox abox show a 0 01 function resetCube b new Box 0 0 0 300 sponge b recursiveCount 0 class Box constructor x y z r_ this pos createVector x y z this r r_ generate let boxes new Array for let x 1 x 2 x for let y 1 y 2 y for let z 1 z 2 z let sum abs x abs y abs z const newR this r 3 if sum 1 let b new Box this pos x x newR this pos y y newR this pos z z newR newR boxes push b return boxes show push translate this pos x this pos y this pos z box this r pop console log click cube to do the Menger Sponge Fractal console log ready script