-
Notifications
You must be signed in to change notification settings - Fork 0
/
mandelbrot.js
453 lines (382 loc) · 13.5 KB
/
mandelbrot.js
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/* globals document, window, history, define, requestAnimationFrame */
"use strict";
!function (name, context, definition) {
if (typeof define == "function") define(definition);
else if (typeof module != "undefined") module.exports = definition();
else context[name] = definition();
}("mandlebrot", this, () => {
// save and set canvas elements
const canvas = document.getElementById("canvas");
const canvasOverlay = document.getElementById("canvasOverlay");
const helpers = {
getEl(id) {
return document.getElementById(id);
},
getParams() {
let params = window.location.search;
const f = {};
params.replace("?", "")
.split("&")
.map((p) => p.split("="))
.forEach((p) => f[p[0]] = p[1]);
return f;
},
getValue(param, value, fallback) {
const params = helpers.getParams();
let ret;
// we need to account for 0 values on purpose
if (params[param] !== undefined) {
ret = params[param];
} else if (value !== undefined) {
ret = value;
} else if (fallback !== undefined) {
ret = fallback;
}
return ret;
},
getBoolean(value) {
if (typeof value === "string") return value == "true";
return value;
}
};
const paramMap = {
maxIterations: "mi",
escapeRadius: "er",
color: "co",
julia: "j",
ci: "ci",
cr: "cr",
zi: "zi",
zr: "zr",
interval: "i"
};
const getInitialInterval = () => {
if (window.innerWidth > window.innerHeight) {
return 1.2 * 2 / window.innerHeight;
} else {
return 1.2 * 2 / window.innerWidth;
}
};
const m = {
state: {
maxIterations: parseInt(helpers.getValue("mi", helpers.getEl("maxIterations").value, 50)),
escapeRadius: parseInt(helpers.getValue("er", helpers.getEl("escapeRadius").value, 5)),
color: helpers.getBoolean(helpers.getValue("co", helpers.getEl("color").checked, false)),
julia: helpers.getBoolean(helpers.getValue("j", helpers.getEl("julia").checked, false)),
ci: parseFloat(helpers.getValue("ci", 0.15)),
cr: parseFloat(helpers.getValue("cr", -0.79)),
zi: parseFloat(helpers.getValue("zi", 0)),
zr: parseFloat(helpers.getValue("zr", 0)),
interval: parseFloat(helpers.getValue("i", getInitialInterval()))
},
yPixel: 0, // the Y value of the canvas row we are on, used to track how close we are to being done
numUpdates: 0, // used for batch updating to only update DOM once per tick
y: null, // the max y value of the complex plane, set in m.draw()
lastUpdatedAt: 0, // for tracking render time
totalTime: document.getElementById("totalTime"),
getXMax() {
return m.state.zr + (m.state.interval * canvas.width / 2);
},
getXMin() {
return m.state.zr - (m.state.interval * canvas.width / 2);
},
getYMax() {
return m.state.zi + (m.state.interval * canvas.height / 2);
},
getYMin() {
return m.state.zi - (m.state.interval * canvas.height / 2);
},
getInitialInterval,
// https://gist.github.com/mjackson/5311256#file-color-conversion-algorithms-js-L119
hsvToRgb(h, s, v) {
let r, g, b;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [ r * 255, g * 255, b * 255 ];
},
getColor(iterations) {
// smooth color by adjusting iteration count
const n = iterations.number - Math.log2(Math.log2(iterations.absoluteValue));
// grayscale
if (!m.state.color) {
const value = 255 - (n / m.state.maxIterations * 255);
return [value, value, value];
}
// color
const value = n / m.state.maxIterations;
// adjusting hue and value to make colors look better (blue only)
// return m.hsvToRgb(.5 + value / 2, 1, 1 - value);
return m.hsvToRgb(Math.abs(value), 1, 1 - value);
},
getIterations(real, imaginary) {
let Zr = m.state.julia ? real : 0,
Zi = m.state.julia ? imaginary : 0,
tempR,
tempI,
n = 0,
abs = 0,
Cr = m.state.julia ? m.state.cr : real,
Ci = m.state.julia ? m.state.ci : imaginary;
for ( ; n < m.state.maxIterations && abs <= m.state.escapeRadius; n++) {
tempR = Math.pow(Zr, 2) - Math.pow(Zi, 2) + Cr;
tempI = 2 * Zr * Zi + Ci;
Zr = tempR;
Zi = tempI;
abs = Math.sqrt(Math.pow(Zr, 2) + Math.pow(Zi, 2));
}
return { number: n, absoluteValue: abs };
},
updateProgressLine(yPixel) {
m.overlayCtx.clearRect(0, 0, canvasOverlay.width, canvasOverlay.height);
if (yPixel) {
m.overlayCtx.beginPath();
m.overlayCtx.moveTo(0, yPixel);
m.overlayCtx.lineTo(canvasOverlay.width, yPixel);
m.overlayCtx.stroke();
}
},
drawSingleLine(x) {
let offset = 0;
const xMax = m.getXMax();
// build line of pixel data to render
for(; x <= xMax; x += m.state.interval) {
const iterations = m.getIterations(x, m.y);
const color = m.getColor(iterations);
m.imgData.data[offset++] = color[0];
m.imgData.data[offset++] = color[1];
m.imgData.data[offset++] = color[2];
m.imgData.data[offset++] = 255;
}
},
draw() {
if (!m.startTime) m.startTime = Date.now();
if (!m.y) m.y = m.getYMax();
m.yPixel++; // update canvas row we are on for this iteration
const xMin = m.getXMin();
m.drawSingleLine(xMin);
m.ctx.putImageData(m.imgData, 0, m.yPixel);
m.y -= m.state.interval;
if (m.yPixel <= window.innerHeight) {
// not done, keep drawing
if (Date.now() - m.lastUpdatedAt > 75) {
// throttle updating DOM
m.lastUpdatedAt = Date.now();
m.updateProgressLine(m.yPixel);
// go to next animation frame so DOM can update
requestAnimationFrame(m.draw);
} else {
m.draw();
}
} else {
// done drawing, reset
m.lastUpdatedAt = 0;
m.yPixel = 0;
m.y = m.getYMax();
m.updateProgressLine();
m.totalTime.textContent = `${(Date.now() - m.startTime) / 1000}s`; // TODO make this state change?
m.startTime = null;
}
},
getParams() {
const params = [];
for (let key in m.state) {
params.push(`${paramMap[key]}=${m.state[key]}`);
}
return `?${params.join("&")}`;
},
pushState(replace) {
if (replace) {
history.replaceState(m.state, "Mandelbrot", m.getParams());
} else {
history.pushState(m.state, "Mandelbrot", m.getParams());
}
},
onPopState(e) {
// TODO do I really need this as separate method?
m.setState(e.state, null, true);
m.y = m.getYMax();
},
render(noPushState) {
if (m.numUpdates !== 0) m.numUpdates--; // only reduce if we've qeued up some updates
if (m.numUpdates === 0) { // wait till all updates are made
// update DOM
for (let prop in m.state) {
const el = helpers.getEl(prop);
if (el) {
const value = m.state[prop];
if (typeof value === "boolean") {
el.checked = value;
} else {
el.value = value;
}
}
}
m.draw();
if (!noPushState) m.pushState();
}
},
setState(id, value, noPushState) {
if (typeof id === "string") {
m.numUpdates++;
m.state[id] = value;
requestAnimationFrame(m.render.bind(this, noPushState));
} else {
// object
for (let prop in id) {
m.setState(prop, id[prop], noPushState);
}
}
},
reset() {
m.setState({
maxIterations: 50,
escapeRadius: 5,
color: false,
zi: 0,
zr: 0,
interval: m.getInitialInterval()
});
m.y = m.getYMax();
},
bindListeners() {
window.addEventListener("popstate", m.onPopState);
// debounce this event
window.addEventListener("resize", ( () => {
let timeout;
return () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
// do resize stuff
m.initCanvas();
m.render(true);
}, 200);
};
} )());
helpers.getEl("reset").addEventListener("click", m.reset);
helpers.getEl("download").addEventListener("click", () => {
const string = canvas.toDataURL("image/png");
const iframe = `<iframe src='${string}' frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe></iframe>`;
const win = window.open("", "_blank");
win.document.open();
win.document.write(iframe);
win.document.close();
});
// INPUT CONTROLS
helpers.getEl("maxIterations").addEventListener("change", (e) => m.setState("maxIterations", parseInt(e.target.value)));
helpers.getEl("escapeRadius").addEventListener("change", (e) => m.setState("escapeRadius", parseInt(e.target.value)));
helpers.getEl("color").addEventListener("change", (e) => m.setState("color", e.target.checked));
helpers.getEl("julia").addEventListener("change", (e) => {
m.setState({
maxIterations: 50,
escapeRadius: 5,
julia: e.target.checked,
zi: 0,
zr: 0,
interval: m.getInitialInterval()
});
m.y = m.getYMax();
});
helpers.getEl("ci").addEventListener("change", (e) => m.setState("ci", parseFloat(e.target.value)));
helpers.getEl("cr").addEventListener("change", (e) => m.setState("cr", parseFloat(e.target.value)));
// DRAG ZOOMING
let zoomBox = null;
["mousedown", "touchstart"].forEach((downEvent) => {
canvasOverlay.addEventListener(downEvent, (e) => {
zoomBox = [e.clientX || e.touches[0].clientX, e.clientY || e.touches[0].clientY, 0, 0];
});
});
// store on m to test?
const getDragBoxY = (y1, x1, x2, isDown) => {
if (isDown) {
return y1 + (( x2 - x1) / m.ratio);
} else {
return y1 - (( x2 - x1) / m.ratio);
}
};
["mousemove", "touchmove"].forEach((moveEvent) => {
canvasOverlay.addEventListener(moveEvent, (e) => {
if (zoomBox) {
// clear out old box first
m.overlayCtx.clearRect(0, 0, canvasOverlay.width, canvasOverlay.height);
// draw new box keeping aspect ratio
zoomBox[2] = e.clientX || e.touches[0].clientX;
const y = e.clientY || e.touches[0].clientY;
let isDown = false;
// messy but gives us fixed drag box sizing and from any direction
if (zoomBox[2] > zoomBox[0]) {
// dragging to right
if (zoomBox[1] < y) isDown = true; // dragging down
} else {
// dragging to left
if (zoomBox[1] > y) isDown = true; // dragging down
}
zoomBox[3] = getDragBoxY(zoomBox[1], zoomBox[0], zoomBox[2], isDown);
m.overlayCtx.strokeRect(zoomBox[0], zoomBox[1], zoomBox[2] - zoomBox[0], zoomBox[3] - zoomBox[1]);
}
});
});
["mouseup", "touchend"].forEach((upEvent) => {
canvasOverlay.addEventListener(upEvent, () => {
m.overlayCtx.clearRect(0, 0, canvasOverlay.width, canvasOverlay.height);
const getVal = (pixel) => {
return pixel * m.state.interval;
};
const xStartValue = zoomBox[0] < zoomBox[2] ? zoomBox[0] : zoomBox[2];
const yStartValue = zoomBox[1] < zoomBox[3] ? zoomBox[1] : zoomBox[3];
m.setState({
interval: Math.abs(getVal(zoomBox[2]) - getVal(zoomBox[0])) / canvas.width,
zr: m.getXMin() + getVal(xStartValue) + getVal(Math.abs(zoomBox[2] - zoomBox[0]) / 2),
zi: m.getYMax() - getVal(yStartValue) - getVal(Math.abs(zoomBox[3] - zoomBox[1]) / 2)
});
m.y = m.getYMax();
zoomBox = null;
});
});
const controls = helpers.getEl("controls");
// nav icon
helpers.getEl("navIcon").addEventListener("click", (e) => {
const el = e.target.nodeName === "SPAN" ? e.target.parentNode : e.target;
const className = "open";
el.classList.toggle(className);
if (el.classList.contains(className)) {
controls.style.left = "0px";
} else {
controls.style.left = "-200px";
}
});
},
initCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvasOverlay.width = window.innerWidth;
canvasOverlay.height = window.innerHeight;
m.overlayCtx = canvasOverlay.getContext("2d");
m.overlayCtx.lineWidth = 3;
m.overlayCtx.strokeStyle = "#FF00FF";
m.ctx = canvas.getContext("2d");
m.ratio = canvas.width / canvas.height;
m.imgData = m.ctx.createImageData(canvas.width, 1);
},
init() {
m.bindListeners();
m.initCanvas();
m.render(true);
m.pushState(true);
}
};
return {
helpers,
m
};
});