Created
December 3, 2022 19:59
-
-
Save machour/77dcb8b135a9dd6cc24b1c40d07e340d to your computer and use it in GitHub Desktop.
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
<html> | |
<head> | |
<title>Mandelbrot Set</title> | |
</head> | |
<body> | |
<canvas id="mandelbrot" width="800" height="600"></canvas> | |
<script> | |
const canvas = document.getElementById('mandelbrot'); | |
const ctx = canvas.getContext('2d'); | |
const width = canvas.width; | |
const height = canvas.height; | |
const maxIterations = 1000; | |
const escapeRadius = 20; | |
const palette = new Uint8Array(256 * 3); | |
for (let i = 0; i < 256; i++) { | |
palette[i * 3] = i; | |
palette[i * 3 + 1] = i; | |
palette[i * 3 + 2] = i; | |
} | |
const scaleX = 3.0 / width; | |
const scaleY = 2.0 / height; | |
function mandelbrot(cx, cy) { | |
let x = 0; | |
let y = 0; | |
for (let i = 0; i < maxIterations; i++) { | |
const xx = x * x; | |
const yy = y * y; | |
const xy = x * y; | |
x = xx - yy + cx; | |
y = xy + xy + cy; | |
if (xx + yy > escapeRadius) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
for (let y = 0; y < height; y++) { | |
for (let x = 0; x < width; x++) { | |
const cx = x * scaleX - 1.5; | |
const cy = y * scaleY - 1; | |
const m = mandelbrot(cx, cy); | |
if (m === -1) { | |
ctx.fillStyle = '#000'; | |
ctx.fillRect(x, y, 1, 1); | |
} else { | |
const color = m % 256; | |
ctx.fillStyle = `rgb(${palette[color * 3]}, ${palette[color * 3 + 1]}, ${palette[color * 3 + 2]})`; | |
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