Created
July 1, 2018 18:41
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.