Skip to content

Instantly share code, notes, and snippets.

@lansana
Created October 21, 2020 03:34
Show Gist options
  • Save lansana/e96c86542696c7cd1628818acbbbb0f6 to your computer and use it in GitHub Desktop.
Save lansana/e96c86542696c7cd1628818acbbbb0f6 to your computer and use it in GitHub Desktop.
// Found on some article, forgot which. It visualizes mandelbrot set.
// TODO: make faster
<!DOCTYPE html>
<html>
<body>
<script>
(() => {
// Create Canvas
const myCanvas = document.createElement('canvas');
myCanvas.width = 1920;
myCanvas.height = 1080;
document.body.appendChild(myCanvas);
const ctx = myCanvas.getContext('2d');
// Start drawing
function checkIfBelongsToMandelbrotSet(x,y) {
let realComponentOfResult = x;
let imaginaryComponentOfResult = y;
// Set max number of iterations
const maxIterations = 350;
for (let i = 0; i < maxIterations; i++) {
const tempRealComponent = realComponentOfResult * realComponentOfResult - imaginaryComponentOfResult * imaginaryComponentOfResult + x;
const tempImaginaryComponent = 2.0 * realComponentOfResult * imaginaryComponentOfResult + y;
realComponentOfResult = tempRealComponent;
imaginaryComponentOfResult = tempImaginaryComponent;
// Return a number as a percentage
if (realComponentOfResult * imaginaryComponentOfResult > 5) {
return (i / maxIterations * 100);
}
}
// Return zero if in set
return 0;
}
// Set appearance settings
const magnificationFactor = 8500;
const panX = 0.8;
const panY = 0.4;
for (let x = 0; x < myCanvas.width; x++) {
for (let y = 0; y < myCanvas.height; y++) {
const belongsToSet = checkIfBelongsToMandelbrotSet(x / magnificationFactor - panX, y / magnificationFactor - panY);
if (belongsToSet === 0) {
// Draw a black pixel
ctx.fillStyle = '#000';
} else {
// Draw a colorful pixel
ctx.fillStyle = `hsl(0, 100%, ${belongsToSet}%)`;
}
ctx.fillRect(x,y, 1,1)
}
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment