Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created May 29, 2024 09:51
Show Gist options
  • Save kujirahand/16d73189242b0e186b38c57f86941417 to your computer and use it in GitHub Desktop.
Save kujirahand/16d73189242b0e186b38c57f86941417 to your computer and use it in GitHub Desktop.
マンデルブロ集合の図形
<!DOCTYPE html><html><head><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>マンデルブロ集合</title>
</head>
<body><canvas id="cnavas" width="800" height="800"></canvas></body>
<script>
// キャンバスと描画用のコンテキストを取得 --- (*1)
const canvas = document.getElementById('cnavas');
const ctx = canvas.getContext('2d');
// 描画の為のパラメータを指定 --- (*2)
const [width, height] = [canvas.width, canvas.height];
const maxIter = 100; // 最大繰返し回数
// マンデルブロ集合の切り取る範囲を指定 --- (*3)
let xMin = -2.0, xMax = 2.0, yMin = -2.0, yMax = 2.0;
// マンデルブロの計算 --- (*4)
function mandelbrot(c) {
let z = { x: 0, y: 0 };
let n = 0;
while (n < maxIter && (z.x * z.x + z.y * z.y) <= 4) {
const xTemp = z.x * z.x - z.y * z.y + c.x;
z.y = 2 * z.x * z.y + c.y;
z.x = xTemp;
n++;
}
return n;
}
// 実際にキャンバスに描画を行う関数 --- (*5)
function draw() {
for (let px = 0; px < width; px++) { // x座標の繰り返し
for (let py = 0; py < height; py++) { // y座標の繰り返し
const x0 = xMin + (xMax - xMin) * px / width;
const y0 = yMin + (yMax - yMin) * py / height;
const c = { x: x0, y: y0 }; // cを指定
const m = mandelbrot(c); // マンデルブロ集合の計算
// 色を計算 --- (*6)
const per = m / maxIter * 100
ctx.fillStyle = (m === maxIter) ? 'white' : `hsl(0, 100%, ${per}%)`;
ctx.fillRect(px, py, 1, 1); // 描画
}
}
}
draw();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment