javascripthtmlcanvas

How to draw a circle in HTML5 Canvas using JavaScript?


How to draw a simple circle in HTML5 Canvas using minimum JavaScript code?


Solution

  • Here is how to draw a circle using JavaScript in HTML5:

    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 70;
    
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
    body {
      margin: 0;
      padding: 0;
    }
    <canvas id="myCanvas" width="578" height="200"></canvas>