# fractal

[browser](../..) ⟩ [canvas](..) ⟩ [examples]() ⟩ fractal

{% tabs %}
{% tab title="💾 程式" %}
![fratal (level: 0 \~ 4)](https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FkrOBwzqSMRAlQOyFy1HF%2Ffractal.png?alt=media\&token=bc2b6741-a03f-4fc4-9ab8-f96a40664fe3)

:floppy\_disk: replit：[canvas polygon fractal](https://replit.com/@pegasusroe/canvas-polygon-fractal#script.js)

⬆️ require： [drawoncanvas2d](../+ext/drawoncanvas2d "mention"), [polygon](polygon "mention")

```javascript
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
```
{% endtab %}

{% tab title="👥 相關" %}
* [koch-snowflake](../state/matrix/koch-snowflake "mention")
* [recursion](../../../appendix/algorithms/recursion "mention")
{% endtab %}
{% endtabs %}
