Skip to content

Instantly share code, notes, and snippets.

@kkuchta
Created July 1, 2018 18:41
Show Gist options
  • Save kkuchta/17b409a48a31433ad0b17e11dba7c8b3 to your computer and use it in GitHub Desktop.
Save kkuchta/17b409a48a31433ad0b17e11dba7c8b3 to your computer and use it in GitHub Desktop.
Tiny mandelbrot renderer. `npm install pngjs-image` then run with `node tiny.js`
const MIN = { x: -2, y: -1 }, MAX = { x: 1, y: 1 };
const WIDTH = HEIGHT = 1000;
function getEscapeCount(c) {
let z = { a: 0, b: 0 };
for (let i = 0; i < 100; i++) {
if (Math.pow(z.a, 2) + Math.pow(z.b, 2) > 4) return i;
z = { a: Math.pow(z.a, 2) - Math.pow(z.b, 2) + c.a, b: z.a * z.b + c.b };
}
}
let image = require('pngjs-image').createImage(WIDTH, HEIGHT);
for (let y = 0; y < HEIGHT; y++) {
const fractalY = MIN.y + ((MAX.y - MIN.y) / HEIGHT * y);
for (let x = 0; x < WIDTH; x++) {
const fractalX = MIN.x + ((MAX.x - MIN.x) / WIDTH * x);
const value = getEscapeCount({a: fractalX, b: fractalY}) == null ? 255 : 0;
image.setAt(x, y, { red: value, green: value, blue: value, alpha: 200 });
}
}
image.writeImage('./out.png');
@kkuchta
Copy link
Author

kkuchta commented Jul 1, 2018

Node that the fractal rendered by this will look a little off due to the limits of JS number precision. Swap out all the math with https://github.com/MikeMcl/bignumber.js to make it look right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment