| Fractals > Smiley Face Fractal Algorithm | |
You can never have enough smileys! How about a smiley fractal algorithm?
This recursive fractal algorithm draws a smiley face. The drawSmiley function draws a single smiley face, and drawSmileyFractal recursively draws smaller smiley faces at the corners of each face.
Take it for a test spin - full code is below - try adjust the parameters as needed to customize the appearance to make the fractals have more emotions.
<!DOCTYPE html> <html> <head> <title>xbdev.net Smiley Face Fractal</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="canvas" width="400" height="400"></canvas> <script> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d');
function drawSmiley(x, y, size) { // Draw face ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.stroke();
// Draw eyes ctx.beginPath(); ctx.arc(x - size / 2, y - size / 4, size / 10, 0, Math.PI * 2); ctx.stroke(); ctx.beginPath(); ctx.arc(x + size / 2, y - size / 4, size / 10, 0, Math.PI * 2); ctx.stroke();
// Draw mouth ctx.beginPath(); ctx.arc(x, y, size * 0.6, Math.PI * 0.2, Math.PI * 0.8); ctx.stroke(); }
function drawSmileyFractal(x, y, size, depth) { drawSmiley(x, y, size); if (depth > 0) { const newSize = size * 0.6; drawSmileyFractal(x - size, y - size, newSize, depth - 1); drawSmileyFractal(x + size, y - size, newSize, depth - 1); drawSmileyFractal(x - size, y + size, newSize, depth - 1); drawSmileyFractal(x + size, y + size, newSize, depth - 1); } }
drawSmileyFractal(canvas.width / 2, canvas.height / 2, 80, 3); </script> </body> </html>
Things to Try • Fill in the smiley faces so they have a solid color (e.g., yellow background)
• Add extra random parameters so each smiley can be slightly different (e.g., bigger/smaller eyes, sad/happy)
• Instead of a 'smiley' try other shapes/patterns, for example, kettles, frogs, flowers, text, ...
• Colors mix in more colors and style
• Explore adding 'depth' (3-dimensional)
• Add a 'save' button so the generated fractal can be exported/saved
• Develop a 'app' page, so the user can select/change options and click 'generate' and it'll build a fractal image
• Modify the 'level of detail' - explore non linear recursion/pattern
| Resources & Links | |
If you like smiley algorithms - you might like another version of the concept which generates lots of different smiley faces by modifying and mixing the various facial features (eyes, mouth and noise)
• Smiley Proof Concept Face Code/Demo (Notebook)
• Smiley Generator Page
|