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);
}