โจfractal
Last updated
Last updated
browser โฉ canvas โฉ examples โฉ fractal
replit๏ผcanvas polygon fractal
โฌ๏ธ require๏ผ drawOnCanvas2D(), regular polygons
const { PI } = Math;
const { log } = console;
function deg(x) { return PI * x / 180 } // degrees
// draw on canvas
drawOnCanvas2D('#playground', (c) => {
const R = 80; // radius
const dx = 20;
const center = [R+dx, R+dx]; // center of fractal
const origin = [0, 0]; // coord system origin
function subfractal(level, r) {
// base case:
if (level === 0) return; // do nothing
// recursive case:
c.save();
c.scale(1/2, 1/2);
c.rotate(PI);
c.polygon(3, ...origin, r, {clockwise: false});
c.restore();
[0, 1, 2].forEach(i => {
c.save();
c.scale(1/2, 1/2);
c.translate(...polar(r, deg(-90) + i * deg(120)).coords);
subfractal(level - 1, r);
c.restore();
})
}
function fractal(level, x, y, r) {
c.save();
c.translate(x, y); // move coord system to center
c.polygon(3, ...origin, r); // outer triangle
subfractal(level, r); // level 4 fractal
c.restore()
}
// fractals from level 0 to 4
[0, 1, 2, 3, 4].forEach(i =>
fractal(i, R + dx + (2*R)*i, R+dx, R)
);
// draw polygons
c.fillStyle = 'hsl(330 80% 50% / 0.3)';
c.fill();
c.stroke();
});im