Skip to content

Instantly share code, notes, and snippets.

@hrickards
Forked from mchapman/mandelbrot.html
Created January 31, 2012 11:04
Show Gist options
  • Save hrickards/1709924 to your computer and use it in GitHub Desktop.
Save hrickards/1709924 to your computer and use it in GitHub Desktop.
Mandelbrot Canvas
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var mandelbrotCanvas = document.getElementById('mandelbrotCanvas');
var context = mandelbrotCanvas.getContext('2d');
var width = mandelbrotCanvas.width;
var height = mandelbrotCanvas.height;
var max_iter = 1000;
var saturation = 80;
var lightness = 50;
for (i=0;i<width;i++) {
for (j=0;j<height;j++) {
var Za = 0;
var Zb = 0;
var Ca = 3*i/(width -1) - 2.25;
var Cb = 2*j/(height-1) - 1;
var iter = 0;
var Zas = 0;
var Zan;
while((Zas + Zb*Zb) < 4 && iter < max_iter) {
Zas = Za*Za;
Zan = Zas - Zb*Zb + Ca;
Zb = 2*Za*Zb + Cb;
Za = Zan;
iter++;
}
if (iter === max_iter) {
context.fillStyle = 'black';
} else {
// Smooth colouring algorithm. See
http://stackoverflow.com/questions/369438
var nsmooth = iter + 1 - Math.log(Math.log(Math.sqrt(Zas
+ Zb*Zb)))/Math.log(2);
var hue = 0.95 + 10*nsmooth;
context.fillStyle = 'hsl(' + hue + ', ' + saturation +
'%, ' + lightness + '%)';
}
context.fillRect(i, j, 1, 1);
}
}
}
</script>
</head>
<body>
<canvas id="mandelbrotCanvas" width="400" height="200">
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment