IFS Fractal

Very naive iterated function system renderer.

Adds colour directly to the canvas each step, without any clever tone mapping. So will tend towards a washed out appearance, if not paused.

Note: canvas is only resized on "generate".

HTML5 canvas disabled?
Generation

Background:
Points Per Frame:
Shape
Shape:
Weight:
Colour:
Rotation
Degrees:
Weight:
Colour:
Spiral
Degrees:
Weight:
Colour:
Sine
Fraction:
Weight:
Colour:

fractal.js

raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
BSD Zero Clause License

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/

window.addEventListener('load', () => {
    'use strict'
    const canvas = document.getElementById('fractalCanvas');
    const graphicsContext = canvas.getContext('2d');

    function hexColorToRgb(hexCol) {
        return [
            parseInt(hexCol.substring(1, 3), 16) / 255,
            parseInt(hexCol.substring(3, 5), 16) / 255,
            parseInt(hexCol.substring(5, 7), 16) / 255,
        ]
    }

    function forEachIn(htmlCollection, ...args) {
        Array.from(htmlCollection).forEach(...args);
    }

    class Operation {
        constructor(params) {
            this.weight = parseInt(params.weight);
            this.color = hexColorToRgb(params.color);
        }

        mixColor(prevColor) {
            for (let i = 0; i < 3; i++) {
                prevColor[i] = (prevColor[i] + this.color[i]) / 2;
            }
            return prevColor;
        }
    };

    class OpRotation extends Operation {
        constructor(params) {
            super(params);
            const angle = params.degrees * Math.PI / 180;
            this.sinTheta = Math.sin(angle);
            this.cosTheta = Math.cos(angle);
        }

        stepPos(coords) {
            const x = coords[0] * this.cosTheta - coords[1] * this.sinTheta;
            const y = coords[0] * this.sinTheta + coords[1] * this.cosTheta;
            coords[0] = x;
            coords[1] = y;
            return coords;
        }
    };

    class OpSpiral extends Operation {
        constructor(params) {
            super(params);
            this.maxAngle = params.degrees * Math.PI / 180;
        }

        stepPos(coords) {
            const angleHere = this.maxAngle * Math.sqrt(
                coords[0] * coords[0] + coords[1] * coords[1]);
            const sinTheta = Math.sin(angleHere);
            const cosTheta = Math.cos(angleHere);
            const x = coords[0] * cosTheta - coords[1] * sinTheta;
            const y = coords[0] * sinTheta + coords[1] * cosTheta;
            coords[0] = x;
            coords[1] = y;
            return coords;
        }
    };

    class OpSine extends Operation {
        constructor(params) {
            super(params);
            this.mulBy = Math.PI * 2 / params.divisor;
        }

        stepPos(coords) {
            coords[0] = Math.sin(coords[0] * this.mulBy);
            coords[1] = Math.sin(coords[1] * this.mulBy);
            return coords;
        }
    };

    class OpCoreShape extends Operation {
        constructor(params) {
            super(params);
            switch (params.shape) {
                case 'pentagon':
                    this.sides = 5;
                    this.scaleFactor = (3 - Math.sqrt(5)) / 2;
                    break;
                case 'hexagon':
                    this.sides = 6;
                    this.scaleFactor = 1/3;
                    break;
                default:
                    this.sides = 3;
                    this.scaleFactor = 0.5;
            }
            this.points = [];
            const sf = 1 - this.scaleFactor;
            for (let i = 0; i < this.sides; i++) {
                const angle = i * Math.PI * 2 / this.sides + Math.PI;
                this.points.push([Math.sin(angle) * sf, Math.cos(angle) * sf]);
            }
        }

        stepPos(coords) {
            const tarPoint = this.points[
                Math.floor(Math.random() * this.sides)];
            coords[0] = coords[0] * this.scaleFactor + tarPoint[0];
            coords[1] = coords[1] * this.scaleFactor + tarPoint[1];
            return coords;
        }
    };

    const availableOperators = {
        OpRotation,
        OpSpiral,
        OpSine,
        OpCoreShape,
    };

    function paramsFromControl(section) {
        const params = {};
        const ctrls = section.querySelectorAll(
            'input[data-param-name], select[data-param-name]');
        ctrls.forEach(c => {
            params[c.dataset.paramName] = c.value;
        });
        return params;
    }

    let generatorAnimId = null;
    let genFunc = null;

    // collect control elements
    let operatorControlSections;
    const generatorParamControls = {};
    const buttons = {};
    {
        const controlRoot = document.getElementById('fractalCtrls');
        const sectionList = Array.from(
            controlRoot.getElementsByClassName('control-section'));

        operatorControlSections = sectionList.filter(
            s => s.dataset?.operation != 'Generation');

        const generationSection = sectionList.filter(
            s => s.dataset?.operation == 'Generation')[0];

        forEachIn(generationSection.getElementsByTagName('input'),
            e => generatorParamControls[e.dataset.paramName] = e);
        forEachIn(generationSection.getElementsByTagName('button'),
            b => buttons[b.dataset.func] = b);

        buttons.pause.disabled = true;
        buttons.resume.disabled = true;
    }

    function beginGenerate() {
        if (generatorAnimId) {
            window.cancelAnimationFrame(generatorAnimId);
            generatorAnimId = null;
        }
        const operatorList = [];
        // collect parameters and create operators.
        operatorControlSections.forEach(section => {
            const opType = section.dataset.operation;
            const op = new availableOperators['Op' + opType](
                paramsFromControl(section));
            const curOpCount = operatorList.length;
            operatorList.length = curOpCount + op.weight;
            operatorList.fill(op, curOpCount, curOpCount + op.weight);
        });
        const pointsPerFrame = generatorParamControls.points.valueAsNumber;
        const bgColor = generatorParamControls.background.value;
        canvas.style.background = bgColor;

        // clear canvas and set up coord system.
        canvas.width = canvas.clientWidth;
        canvas.height = canvas.clientHeight;
        graphicsContext.resetTransform();
        graphicsContext.clearRect(0, 0, canvas.width, canvas.height);

        const sideLen = Math.min(canvas.width, canvas.height);
        graphicsContext.translate(canvas.width / 2, canvas.height / 2);
        graphicsContext.scale(sideLen / 2, sideLen / 2);

        const pixSize = 0.8 / sideLen;

        // start drawing
        let point = [Math.random() * 2 - 1, Math.random() * 2 - 1];
        let color = [0.0, 0.0, 0.0];

        function iterStep() {
            const choice = Math.floor(Math.random() * operatorList.length);
            const op = operatorList[choice];
            op.stepPos(point);
            op.mixColor(color);
        }
        function drawPoint()
        {
            graphicsContext.fillStyle = `rgba(
                ${Math.floor(color[0] * 255)},
                ${Math.floor(color[1] * 255)},
                ${Math.floor(color[2] * 255)},
                0.5)`;
            graphicsContext.fillRect(point[0], point[1], pixSize, pixSize);
        }

        // run it for a bit to get close to the shape
        for (let i = 100; i-- > 0;) {
            iterStep();
        }

        function drawFrame() {
            for (let i = pointsPerFrame; i-- > 0;) {
                iterStep();
                drawPoint();
            }
            generatorAnimId = window.requestAnimationFrame(drawFrame);
        }

        genFunc = drawFrame;

        drawFrame();
    }

    function updateButtons() {
        if (genFunc) {
            if (generatorAnimId) {
                buttons.pause.disabled = false;
                buttons.resume.disabled = true;
            } else {
                buttons.pause.disabled = true;
                buttons.resume.disabled = false;
            }
        }
    }

    buttons.generate.addEventListener('click', () => {
        beginGenerate();
        updateButtons();
    });

    buttons.pause.addEventListener('click', () => {
        if (generatorAnimId) {
            window.cancelAnimationFrame(generatorAnimId);
            generatorAnimId = null;
        }
        updateButtons();
    });

    buttons.resume.addEventListener('click', () => {
        if (!generatorAnimId && genFunc) {
            generatorAnimId = window.requestAnimationFrame(genFunc);
        }
        updateButtons();
    });
});