HTML Canvas

HTML <canvas> is used to create graphics in HTML. We create the graphics inside the <canvas> using JavaScript. For example,

<canvas id="circle-canvas" height="200" width="200" style="border: 1px solid;"></canvas>
<script>
    let canvas = document.getElementById("circle-canvas");
    let ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(100, 100, 80, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'blue';
    ctx.fill();
</script>

Browser Output

A Circle Canvas

Here, we are using JavaScript along with the Canvas API to create a circle inside the canvas. This code creates a simple drawing using the canvas element in an HTML page.

The canvas has an id circle-canvas and dimensions of 200x200 pixels. This creates a surface on which we can draw using JavaScript.

We have used the getContext() method of the canvas element and stored it in the ctx variable. It allows us to access the drawing context and draw on the canvas.

In the above example,

  • beginPath() - creates a new path, any subsequent path commands will start from this point
  • arc() - draws a circle where,
    the circle is centered at (100, 100)
    the circle has a radius of 80 pixels
    the circle is drawn to cover the entire circumference in a counter-clockwise direction, by starting at 0 radians and ending at 2*Math.PI radians
  • fillStyle - sets the fill color of the circle to blue
  • fill()- fills the circle with the blue color

Table of Contents

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges