Last active
December 6, 2019 08:48
-
-
Save rozek/250e88a2993114b6376feb93c89e9929 to your computer and use it in GitHub Desktop.
Bangle.js: displays a Mandelbrot set with 120x120 px resolution
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
Bangle.setLCDMode('120x120'); | |
g.clear(); | |
const Width = g.getWidth(); | |
const Height = g.getHeight(); | |
/**** color mapping (especially for Bangle.js) ****/ | |
function PaletteEntry (r,g,b) { // 8-bit modes use the "web color palette" | |
return r*36 + g*6 + b; | |
} | |
let ColorMap = [0]; // not part of Mandelbrot set? then leave pixel black | |
for (let i = 0; i < 3; i++) { | |
ColorMap.push(PaletteEntry(i,i,5)); | |
} | |
for (let i = 3; i < 6; i++) { | |
ColorMap.push(PaletteEntry(i,i,5)); | |
ColorMap.push(PaletteEntry(i,i,5)); | |
ColorMap.push(PaletteEntry(i,i,5)); | |
ColorMap.push(PaletteEntry(i,i,5)); | |
} | |
const ColorCount = ColorMap.length; | |
/**** EscapeTimeOf ****/ | |
const maxIterations = ColorCount; | |
function EscapeTimeOf (x,y) { // slightly optimized | |
let re = x, imag = y; | |
let r2 = x*x, i2 = y*y, z2 = (x+y)*(x+y); | |
for (let i = 0; i < maxIterations; i++) { | |
let newRe = r2 - i2 + x; | |
let newImag = z2 - r2 - i2 + y; | |
r2 = newRe*newRe; | |
i2 = newImag*newImag; | |
z2 = (newRe+newImag)*(newRe+newImag); | |
if (r2 + i2 > 4) { return i } | |
} | |
return 0; | |
} | |
/**** draw Mandelbrot set ****/ | |
const xOffset = -1.9; const Zoom = 50; | |
const yOffset = -1.2; | |
for (let y = 0; y < Height; y++) { | |
for (let x = 0; x < Width; x++) { | |
let EscapeTime = EscapeTimeOf( | |
xOffset + x/Zoom, yOffset + y/Zoom | |
); | |
if (EscapeTime > 0) { | |
g.setPixel(x,y,ColorMap[EscapeTime]); | |
} | |
} | |
} | |
g.flip(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment