Skip to content

Instantly share code, notes, and snippets.

@nkrth
Forked from drcircuit/mandel.js
Created February 13, 2019 17:19
Show Gist options
  • Save nkrth/0a56b756d277fea6c822c9d50e859064 to your computer and use it in GitHub Desktop.
Save nkrth/0a56b756d277fea6c822c9d50e859064 to your computer and use it in GitHub Desktop.
Generalized Mandelbrot in JavaScript
/** mandel5 */
// Uses DrCiRCUiT's Canvas Library, but you can change the drawing / canvas methods for something else.
(function () {
var scr;
var plane = {
real: { min: -2, max: 2 },
imag: { min: -2, max: 2 }
};
function setup() {
scr = dcl.setupScreen(512, 512);
scr.setBgColor('black');
document.body.style.backgroundColor = 'black';
}
function scale(n, min, max, omin, omax){
return n * (max - min) / (omax - omin) + min;
}
function complex(real, imag){
let abs = Math.sqrt(real * real + imag * imag);
return {
r: real,
i: imag,
abs: abs,
add: function(z){
return complex(real + z.r, imag + z.i);
},
mul: function(z){
let r = real * z.r + imag * z.i * -1;
let i = real * z.i + imag * z.r;
return complex(r,i);
},
pow: function(n){
let abston = Math.pow(abs, n);
let theta = Math.atan2(imag, real);
let r = abston * Math.cos(theta * n);
let i = abston * Math.sin(theta*n);
return complex(r,i);
}
};
}
function mandel(c, maxItertions, escapeRadius, power){
let z = complex(0,0);
for(var i = 0;i<maxIterations;i++){
z = z.pow(power).add(c);
if(z.abs > escapeRadius){
break;
}
}
return {
z: z,
i: i
}
}
function ship(c, maxItertions, escapeRadius, power){
let z = complex(0,0);
for(var i = 0;i<maxIterations;i++){
z = complex(Math.abs(z.r), Math.abs(z.i));
z = z.pow(power).add(c);
if(z.abs > escapeRadius){
break;
}
}
return {
z: z,
i: i
}
}
let maxIterations = 25;
let escapeRadius = 2;
let power = 3;
function draw() {
for (let x = 0; x < scr.width; x++) {
for (let y = 0; y < scr.height; y++) {
//Map x,y to complex real, imag
let r = scale(x, plane.real.min, plane.real.max, 0, scr.width);
let i = scale(y, plane.imag.min, plane.imag.max, 0, scr.height);
//Make complex number
let c = complex(r,i);
//Run Mandelbrot
let res = mandel(c, maxIterations, escapeRadius,power);
//let res = ship(c, maxIterations, escapeRadius,power);
//Check if diverged
if(res.z.abs > escapeRadius){
let alpha = (res.i - Math.log(res.z.abs) / Math.log(2)) / maxIterations * 2;
dcl.rect(x,y,1,1,"rgba(255,0,0,"+alpha.toFixed(2)+")");
}
if(res.z.abs < escapeRadius){
let alpha = (res.z.abs - Math.log(res.z.abs) / Math.log(power)) / maxIterations *.2;
dcl.rect(x,y,1,1,"rgba(255,0,0,"+alpha.toFixed(2)+")");
}
}
}
}
setup();
draw();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment