Skip to content

Instantly share code, notes, and snippets.

@AhsanAyaz
Created July 7, 2024 21:04
Show Gist options
  • Save AhsanAyaz/a4e232d4f1aadaa1005585c9ed852186 to your computer and use it in GitHub Desktop.
Save AhsanAyaz/a4e232d4f1aadaa1005585c9ed852186 to your computer and use it in GitHub Desktop.
A simple web app showing how to create a spirograph with just html and javascript using SVG and line elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Spirograph</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,200..1000;1,200..1000&display=swap"
rel="stylesheet"
/>
<style>
body {
font-family: "Nunito", sans-serif;
font-optical-sizing: auto;
background-color: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
svg {
border: 1px solid white;
}
.mainH {
color: white;
text-align: center;
}
a {
color: lightblue;
}
</style>
</head>
<body>
<div class="container">
<h1 class="mainH">
Follow on <a target="_blank" href="https://github.com/ahsanayaz">GitHub</a>
</h1>
<svg id="drawing" width="600" height="600"></svg>
</div>
<script>
const svg = document.getElementById("drawing");
const colors = ["red", "yellow", "blue", "green", "purple", "orange"];
let angle = 0;
let x = 300,
y = 300;
let i = 0;
function drawStep() {
if (i >= 300) return;
const color = colors[i % 6];
const length = i * 2;
const x1 = x + length * Math.cos((angle * Math.PI) / 180);
const y1 = y + length * Math.sin((angle * Math.PI) / 180);
const line = document.createElementNS(
"http://www.w3.org/2000/svg",
"line"
);
line.setAttribute("x1", x);
line.setAttribute("y1", y);
line.setAttribute("x2", x1);
line.setAttribute("y2", y1);
line.setAttribute("stroke", color);
line.setAttribute("stroke-width", 2);
svg.appendChild(line);
x = x1;
y = y1;
angle += 61;
i++;
setTimeout(drawStep, 50); // 50 milliseconds delay
}
drawStep();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment