How to draw a star by using canvas HTML5?

Drawing on the HTML canvas is to be done with JavaScript. Use the HTML DOM Method getElementById() and getContext() before drawing on the canvas. To draw a star in HTML, use the canvas element.

With canvas, use the lineTo() method to draw a star. The lineTo() method includes x and y parameter values, which positions the lines to help you in drawing.

To draw canvas on HTML document:


You can try to run the following code to draw a star using HTML5 canvas

      <title>HTML5 Canvas Tag</title>
      <canvas id="newCanvas" width="300" height="250"></canvas>
         var canvas = document.getElementById('newCanvas');
         var ctx = canvas.getContext('2d');
         ctx.fillStyle = "blue";
         ctx.moveTo(108, 0.0);
         ctx.lineTo(141, 70);
         ctx.lineTo(218, 78.3);
         ctx.lineTo(162, 131);
         ctx.lineTo(175, 205);
         ctx.lineTo(108, 170);
         ctx.lineTo(41.2, 205);
         ctx.lineTo(55, 131);
         ctx.lineTo(1, 78);
         ctx.lineTo(75, 68);
         ctx.lineTo(108, 0);


Updated on: 16-Dec-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started