Code runs on Chrome although code can be tweaked to run on Safari and Firefox.

The following code paints a fractal on an HTML 5 canvas using a web worker. A web worker mimics a program thread thus allowing the browser to perform heavy operations without affecting the user experience.

Main HTML file

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
var c = document.getElementById('content');
g = c.getContext('2d');
WIDTH = c.width;
HEIGHT = c.height;
g.fillStyle = '#000000';
g.fillRect(0,0,WIDTH,HEIGHT);
var worker = new Worker('fractal.js');
worker.onmessage = function(event) {
g.fillStyle = event.data.col;
g.fillRect(event.data.x,event.data.y,1,1);
}
worker.postMessage();
});
</script>
</head>
<body>
<canvas width="640" height="480" id="content"></canvas>
</body>
</html>

fractal.js

self.onmessage = function(e) {
minx = -2;
maxx = 1;
miny = -1;
maxy = 1;
max_iteration = 50;
for (xp=0;xp<640;xp++) {
for (yp=0;yp<480;yp++) {
x0 = ((maxx-minx)*(xp/640))+minx;
y0 = ((maxy-miny)*(yp/480))+miny;
x = 0;
y = 0;
iteration = 0;
while (((x*x) + (y*y)) < (2*2) && iteration<max_iteration) {
xtemp = (x*x) - (y*y) + x0;
y = (2*x*y) + y0;
x = xtemp;
iteration = iteration + 1;
}
if (iteration==max_iteration) {
self.postMessage({'x':xp,'y':yp,'col':'#000000'});
} else {
self.postMessage({'x':xp,'y':yp,'col':'#'+(iteration*100).toString(16)});
}
}
}
}
Share