Created
October 21, 2020 03:34
-
-
Save lansana/e96c86542696c7cd1628818acbbbb0f6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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