HTML5 Game - Canvas Circle

Introduction

The HTML5 canvas API doesn't support a circle method.

We can create a circle by drawing a fully enclosed arc.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                /* ww w .j  a  v  a2 s  .c  o m*/
                context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 * Math.PI, false);
                context.fillStyle = "#8ED6FF";
                context.fill();
                context.lineWidth = 5;
                context.strokeStyle = "black";
                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

We can create an arc using the arc() method.

It draws a section of a circle by a starting angle and an ending angle.

We can draw circle by setting the angle between the starting angle and ending angle as 360 degrees (2pi).

context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);  

Related Topics