gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
Make a Mandelbrot set in JavaScript HTML5 CSS please
- User
Make a Mandelbrot set in JavaScript HTML5 CSS please
- Assistant
Make a Mandelbrot set in JavaScript HTML5 CSS please
To draw a Mandelbrot set using HTML5's <canvas> element and JavaScript, we will create a simple webpage with a <canvas>, and we will write JavaScript code to render the Mandelbrot set. Here's a basic example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mandelbrot Set</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="mandelbrotCanvas" width="800" height="800"></canvas>
<script>
const canvas = document.getElementById('mandelbrotCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const maxIter = 1000;
const zoom = 200;
const panX = 2;
const panY = 1.5;
function mandelbrotSet() {
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
let real = (x - width / 2) / zoom - panX;
let imag = (y - height / 2) / zoom - panY;
let cReal = real;
let cImag = imag;
let n = 0;
while (n < maxIter) {
const realPart = real * real - imag * imag;
const imagPart = 2 * real * imag;
real = realPart + cReal;
imag = imagPart + cImag;
if (real * real + imag * imag > 4) break;
n++;
}
const color = map(n, 0, maxIter, 0, 255);
drawPixel(x, y, color, color, color, 255);
}
}
}
function drawPixel(x, y, red, green, blue, alpha) {
ctx.fillStyle = `rgba(${red},${green},${blue},${alpha / 255})`;
ctx.fillRect(x, y, 1, 1);
}
function map(value, start1, stop1, start2, stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
mandelbrotSet();
</script>
</body>
</html>
In the code above:
canvas element with a specific width and height (800x800 pixels for this example).<style> block, we've added basic styling to center the canvas on the page.<script> block where we define the mandelbrotSet function that does the necessary computations and draws the Mandelbrot set.maxIter variable determines how many times we iterate over each point in the set. The higher the value, the more detailed the drawing, but it will also take longer to compute.zoom variable to control the scale, and panX and panY to center the set on the canvas.drawPixel function fills in a single pixel on the canvas with a color based on how many iterations it took for the point to escape to infinity (or determine that it's bounded).map function is a utility to convert a value from one range to another.Open this HTML code in your web browser to see the Mandelbrot set drawn out on the canvas. You can experiment with the maxIter, zoom, panX, and panY variables to alter the appearance of the Mandelbrot set.
Not yet included in a published release.