Public
Edited
Nov 21, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
drawKochSnowflake(depth, 800, 800, "#e0f7fa", "#006064")
Insert cell
function drawKochSnowflake(
depth = 3,
canvasWidth = 600,
canvasHeight = 600,
bgColor = "#ffffff",
lineColor = "#000000"
) {
const canvas = document.getElementById("kochCanvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const ctx = canvas.getContext("2d");

// Clear the canvas
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);

// Helper function to draw the Koch curve
function drawKochSegment(x1, y1, x2, y2, depth) {
if (depth === 0) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = lineColor;
ctx.stroke();
return;
}

const dx = (x2 - x1) / 3;
const dy = (y2 - y1) / 3;

const xA = x1 + dx;
const yA = y1 + dy;

const xB = x2 - dx;
const yB = y2 - dy;

const xPeak = xA + dx * Math.cos(Math.PI / 3) - dy * Math.sin(Math.PI / 3);
const yPeak = yA + dx * Math.sin(Math.PI / 3) + dy * Math.cos(Math.PI / 3);

// Recursively draw each segment
drawKochSegment(x1, y1, xA, yA, depth - 1);
drawKochSegment(xA, yA, xPeak, yPeak, depth - 1);
drawKochSegment(xPeak, yPeak, xB, yB, depth - 1);
drawKochSegment(xB, yB, x2, y2, depth - 1);
}

// Initial triangle coordinates
const size = Math.min(canvasWidth, canvasHeight) * 0.6;
const xCenter = canvasWidth / 2;
const yCenter = canvasHeight / 2;
const height = (size * Math.sqrt(3)) / 2;

const x1 = xCenter - size / 2;
const y1 = yCenter + height / 3;

const x2 = xCenter + size / 2;
const y2 = y1;

const x3 = xCenter;
const y3 = yCenter - (2 * height) / 3;

// Draw the snowflake
drawKochSegment(x1, y1, x2, y2, depth);
drawKochSegment(x2, y2, x3, y3, depth);
drawKochSegment(x3, y3, x1, y1, depth);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more