JavaScript > Browser APIs > Canvas API > Drawing shapes

Drawing a Circle with Canvas API

This code snippet demonstrates how to draw a circle (or an arc) on an HTML canvas using the Canvas API in JavaScript. We'll cover setting up the canvas, defining the circle's properties (center coordinates, radius, color), and then drawing it using the `arc` method.

Setting up the Canvas

As before, we first retrieve the HTML canvas element and its 2D rendering context. We also explicitly set the width and height of the canvas. Remember to include `` in your HTML.

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

canvas.width = 400; // Set canvas width
canvas.height = 200; // Set canvas height

Defining Circle Properties

Here, we define the properties of the circle. `centerX` and `centerY` specify the coordinates of the center of the circle. `radius` defines the radius of the circle. `startAngle` and `endAngle` define the starting and ending angles of the arc (in radians). To draw a complete circle, the `endAngle` should be 2 * Math.PI. `circleColor` sets the fill color for the circle.

const centerX = 200; // X-coordinate of the circle's center
const centerY = 100; // Y-coordinate of the circle's center
const radius = 50; // Radius of the circle
const startAngle = 0; // Start angle in radians
const endAngle = 2 * Math.PI; // End angle in radians (full circle)
const circleColor = 'orange'; // Color of the circle

Drawing the Circle

Before drawing, we call `ctx.beginPath()` to start a new path. This is important to avoid unexpected connections to previous drawings. Then, we use the `arc` method to define the circle's arc. The `arc` method takes five arguments: the x-coordinate of the center, the y-coordinate of the center, the radius, the start angle, and the end angle. Finally, we set the `fillStyle` and call `fill` to fill the circle with the specified color.

ctx.beginPath(); // Start a new path
ctx.arc(centerX, centerY, radius, startAngle, endAngle); // Define the arc
ctx.fillStyle = circleColor; // Set the fill color
ctx.fill(); // Fill the circle

Complete Code Example

This is the complete code, copy paste to your project and you can see the circle!

<canvas id="myCanvas"></canvas>
<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');

  canvas.width = 400;
  canvas.height = 200;

  const centerX = 200;
  const centerY = 100;
  const radius = 50;
  const startAngle = 0;
  const endAngle = 2 * Math.PI;
  const circleColor = 'orange';

  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, startAngle, endAngle);
  ctx.fillStyle = circleColor;
  ctx.fill();
</script>

Understanding Angles in Radians

The `arc` method uses radians for specifying angles. A full circle is 2 * Math.PI radians (approximately 6.28 radians). A half-circle is Math.PI radians. You can convert degrees to radians using the formula: radians = degrees * (Math.PI / 180).

Real-Life Use Case

Drawing circles is fundamental for creating various visual elements, including circular progress bars, pie charts, game characters (e.g., drawing faces), and abstract art.

Best Practices

  • Always call `beginPath()`: Call `beginPath()` before drawing any new shape to avoid unexpected connections to previous paths.
  • Use `closePath()` if needed: If you're drawing a closed shape (like a circle), you can call `closePath()` to explicitly close the path, although it's not strictly necessary for `arc` with a full circle.
  • Understand `arc` parameters: Ensure you correctly understand and use the parameters of the `arc` method: centerX, centerY, radius, startAngle, and endAngle.

Interview Tip

Be prepared to explain how the `arc` method works and the meaning of its parameters. Also, understand the concept of radians and how they are used to define angles in the Canvas API.

When to use them

The Canvas API is ideal for creating dynamic and interactive graphical elements on a webpage. The drawing of circle with arc is suitable for when you want to create pie charts, circular progress bars, or game objects.

Memory footprint

The memory footprint of drawing circles, similar to rectangles, depends primarily on the size of the canvas and the complexity of any applied styles (e.g., gradients, shadows). Drawing numerous circles, especially with complex styling, can increase memory usage. Optimizing the number of drawn objects is crucial.

Alternatives

Similar to rectangles, SVG and WebGL are alternatives. SVG may be more appropriate for simpler, scalable circles, while WebGL is suited for complex 2D or 3D graphics involving many circles.

Pros

  • Flexibility: The Canvas API allows for precise control over the appearance of circles.
  • Performance: Similar to rectangles, for a large number of circles the canvas api can be more performant.

Cons

  • Resolution Dependence: Circles drawn on a canvas are rasterized and may appear pixelated when scaled.
  • Accessibility: Canvas graphics are not inherently accessible to screen readers, requiring extra effort to provide alternative text descriptions.

FAQ

  • Why is my circle not a perfect circle?

    Ensure that the `startAngle` is 0 and the `endAngle` is 2 * Math.PI. Also, make sure that the canvas is not being scaled or distorted by CSS.
  • How do I draw only a portion of a circle (an arc)?

    Modify the `startAngle` and `endAngle` parameters of the `arc` method to define the desired portion of the circle. For example, to draw a half-circle, set `startAngle` to 0 and `endAngle` to Math.PI.
  • How can I draw a circle with a border?

    Use `ctx.stroke()` instead of `ctx.fill()` after defining the arc with `ctx.arc()`. You'll also need to set the `strokeStyle` property of the canvas context to specify the border color and the `lineWidth` property to set the border thickness.