Skip to content

Instantly share code, notes, and snippets.

@keichi
Created January 15, 2013 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keichi/4539473 to your computer and use it in GitHub Desktop.
Save keichi/4539473 to your computer and use it in GitHub Desktop.
Reckless try to render Buddhabrot fractal with JavaScript...
<html>
<head>
<title>Buddhabrot JS</title>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<canvas id="world" width="500" height="500"></canvas>
</body>
</html>
window.onload = function() {
var canvas = document.getElementById('world');
if (!canvas || ! canvas.getContext) {
return false;
}
var startTime = new Date();
var CONVERGENCE_CHECK_LOOP = 10000,
CANVAS_WIDTH = canvas.width,
CANVAS_HEIGHT = canvas.height,
LOOP_COUNT = 1000000,
i = 0,
j = 0;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
var imageData = ctx.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
var data = imageData.data;
var buffer = new Array(CANVAS_WIDTH * CANVAS_HEIGHT);
for (i = 0; i < buffer.length; i++) {
buffer[i] = 0;
}
for (i = 0; i < LOOP_COUNT; i++) {
var xtrack = [],
ytrack = [],
cx = Math.random() * 4.0 - 2.0,
cy = Math.random() * 4.0 - 2.0;
nx = 0.0,
ny = 0.0,
npx = 0.0,
npy = 0.0;
doesConverge = true;
for (j = 0; j < CONVERGENCE_CHECK_LOOP; j++) {
npx = nx * nx - ny * ny + cx;
npy = 2.0 * nx * ny + cy;
nx = npx;
ny = npy;
if (Math.abs(nx) > 2.0 || Math.abs(ny) > 2.0) {
doesConverge = false;
break;
}
xtrack.push(nx);
ytrack.push(ny);
}
if (!doesConverge) {
for (j = 0; j < xtrack.length; j++) {
var x = Math.floor((xtrack[j] + 2.0) / 4.0 * CANVAS_WIDTH),
y = Math.floor((ytrack[j] + 2.0) / 4.0 * CANVAS_HEIGHT),
index = x + y * CANVAS_WIDTH;
buffer[index] += 1;
}
}
}
var max = 0;
for (i = 0; i < buffer.length; i++) {
if (buffer[i] > max) {
max = buffer[i];
}
}
var endTime = new Date();
console.log(String(endTime - startTime) + '[ms] elapsed!');
for (i = 0; i < buffer.length; i++) {
var color = Math.min(255, buffer[i]);
data[i * 4] = color;
data[i * 4+ 1] = color;
data[i * 4+ 2] = color;
data[i * 4+ 3] = 255;
}
ctx.putImageData(imageData, 0.0, 0.0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment