Drawing Star Shape with Different Sides on HTML5 Canvas

Vishwas R
2 min readAug 31, 2023

--

Are you looking to add some visual flair to your web page? Creating geometric shapes like stars using HTML5 Canvas can be a fun and engaging way to enhance your website’s aesthetics. Find the below article that helps you draw star shapes with varying numbers of sides using HTML5 Canvas.

What You’ll Need:

  • Basic understanding of HTML and JavaScript
  • A text editor for coding

Setting Up the HTML5 Canvas:

HTML Structure: Start by creating the basic structure of your HTML file. Include a <canvas> element within the <body> tag, and don't forget to give it an id for easy access using JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>Canvas Star Shapes</title>
</head>
<body>
<canvas id="starCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>

Drawing Star Shape: Now it’s time to create the magic with JavaScript. Create a file named script.js and link it to your HTML file.

var canvas = document.getElementById("starCanvas");
canvas.width = 500;
var ctx = canvas.getContext("2d");// Function to draw a star with 'n' sides
function drawStar(x, y, radius, sides, fillColor) {
var points = sides || 5;
ctx.fillStyle = fillColor;
ctx.beginPath();
ctx.moveTo(x, y + radius);
for (var i = 0; i < 2 * points + 1; i++) {
var r = (i % 2 == 0) ? radius : radius / 2;
var a = Math.PI * i / points;
ctx.lineTo(x + r * Math.sin(a), y + r * Math.cos(a));
};
ctx.closePath();
if (fillColor)
ctx.fill();
}
// Call the drawStar function with different parameters
drawStar(100, 75, 50, 5, "red"); // 5-sided star
drawStar(250, 75, 50, 6, "red"); // 6-sided star
drawStar(400, 75, 50, 8, "red"); // 8-sided star

Expanding Your Creativity:

Now that you’ve successfully drawn 5, 6 & 8-sided stars, you can experiment with different numbers of sides, colors, sizes, and even animation effects.

--

--

Vishwas R

<< Engineer || Software Developer || Techie || Cricketer || Traveler || Blogger >>