Skip to content

Instantly share code, notes, and snippets.

@jsjolund
Created June 25, 2023 20:44
Show Gist options
  • Save jsjolund/70f9c986dae2ce2ea97ba3f6545ba033 to your computer and use it in GitHub Desktop.
Save jsjolund/70f9c986dae2ce2ea97ba3f6545ba033 to your computer and use it in GitHub Desktop.
This HTML file contains JavaScript code that generates a Sierpinski Gasket with 5 iterations of triangles.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sierpinski Gasket with JavaScript</title>
<style>
.small { fill: none; stroke: black; stroke-width: 1; }
</style>
</head>
<body>
<svg id="sierpinskiSVG" xmlns="http://www.w3.org/2000/svg" width="600" height="600" viewBox="0 0 600 600"></svg>
<script>
const svg = document.getElementById('sierpinskiSVG');
function drawTriangle(x, y, size) {
const halfSize = size / 2;
const points = [
[x, y],
[x + size, y],
[x + halfSize, y + (Math.sqrt(3) * halfSize)],
];
const polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute('points', points.map(p => p.join(',')).join(' '));
polygon.setAttribute('class', 'small');
svg.appendChild(polygon);
}
function sierpinski(x, y, size, iterations) {
if (iterations === 0) {
drawTriangle(x, y, size);
} else {
const newSize = size / 2;
sierpinski(x, y, newSize, iterations - 1);
sierpinski(x + newSize, y, newSize, iterations - 1);
sierpinski(x + newSize / 2, y + (Math.sqrt(3) * newSize / 2), newSize, iterations - 1);
}
}
sierpinski(0, 0, 600, 5);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment