Public
Edited
Feb 21, 2024
Insert cell
Insert cell
Insert cell
Insert cell
{
const canvas = html`<canvas width="600" height="600"></canvas>`;
const ctx = canvas.getContext('2d');
// mark the three corners of the initial big triangle on the canvas
const p1 = {x: 0, y: 600}; // p1 is one corner of the triangle—bottom left.
const p2 = {x: 300, y: 0}; // p2 is another corner—top middle
const p3 = {x: 600, y: 600}; // last corner, the bottom right
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSierpinskiTriangle(ctx, p1, p2, p3, depth);
return canvas;
}
Insert cell
Insert cell
Insert cell
function drawSierpinskiTriangle(ctx, p1, p2, p3, depth) {
const drawTriangle = (p1, p2, p3) => {
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.lineTo(p3.x, p3.y);
ctx.closePath();
ctx.stroke();
};

const midpoint = (p1, p2) => ({
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
});

const sierpinski = (p1, p2, p3, depth) => {
if (depth === 0) {
drawTriangle(p1, p2, p3);
} else {
const mid1 = midpoint(p1, p2);
const mid2 = midpoint(p2, p3);
const mid3 = midpoint(p1, p3);
sierpinski(p1, mid1, mid3, depth - 1);
sierpinski(mid1, p2, mid2, depth - 1);
sierpinski(mid3, mid2, p3, depth - 1);
}
};

sierpinski(p1, p2, p3, 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