Skip to content

Instantly share code, notes, and snippets.

@dominiccooney
Last active May 6, 2020 15:33
Show Gist options
  • Save dominiccooney/2dcfaccb153bd2903a8b to your computer and use it in GitHub Desktop.
Save dominiccooney/2dcfaccb153bd2903a8b to your computer and use it in GitHub Desktop.
Julia set in HTML5 canvas
<!DOCTYPE html>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
width: 100vh;
height: 100vh;
}
</style>
<canvas id="c"></canvas>
<script>
'use strict';
class Complex {
constructor(real, imag) {
this._i = real;
this._j = imag;
}
get real() { return this._i; }
get imag() { return this._j; }
add(other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}
mul(other) {
return new Complex(
this.real * other.real - this.imag * other.imag,
this.real * other.imag + this.imag * other.real);
}
abs() {
return Math.sqrt(this.real * this.real + this.imag * this.imag);
}
}
let canvas = document.querySelector('#c');
let ctx = canvas.getContext('2d');
ctx.scale(canvas.width / 3, canvas.height / 3);
ctx.translate(1.5, 1.5);
function draw(step, phase) {
const c = new Complex(0.544, 0);
const num_iter = 360;
for (let v = -1.5; v < 1.5 + 0.5 * step; v += step) {
for (let u = -1.5; u < 1.5 + 0.5 * step; u += step) {
var z = new Complex(u, v);
for (var i = 0; i < num_iter && z.abs() < 2; i++) {
z = z.mul(z).mul(z).mul(z).mul(z).add(c);
}
ctx.fillStyle = 'hsl(' + (phase + 4 * i) + ', 100%, 50%)';
ctx.fillRect(u - 0.5 * step, v - 0.5 * step, step, step);
}
}
}
function go(step, phase) {
if (step * canvas.width < 1.0) {
document.body.style.background = 'black';
return;
}
draw(step, phase);
requestAnimationFrame(() => go(step * 0.9, phase + 10));
}
go(1.0, 0);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment