How to Draw a Circle with JavaScript and HTML5 Canvas

2021-01-12 19:47:02 | #programming #javascript #html5 #canvas

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

JavaScript and the HTML5 canvas element allows us to dynamically render 2D and 3D shapes and bitmap images in the browser. With canvas, we can produce complex graphics, interactions, and physics for simulations and games. In this tutorial, we'll learn how to render circles.

To communicate with Canvas, we have to reference properties and functions provided by the Canvas API, but the code you'll write in this tutorial is native JavaScript. Coding for Canvas is a great way to learn about JavaScript Object Oriented Programming (OOP) and API abstraction.

The following program demonstrates not only how to draw a circle, but program a Circle class that makes it easier to make multiple instances of circles. Try modifying the code below, to change the position, radius, and fill color of the shape. And see if you can figure out how to render multiple circles to the Canvas. Then, skip to the next section to get a detailed explanation.

Code Editor

Components of a Circle

To understand the parameters we have to pass into the ctx.arc() function, we first need to understand the terms we use to define the measurements of a circle.

Radius and Diameter

Radius is the distance between the center of a circle and its perimeter (edge). The diameter is the full distance from edge to edge. And the circumference is the measurement of the entire perimiter, calculated with the formula 2πr or 2 * PI * radius.

Angle and Rotation in the HTML Canvas

In a standard system, positive degrees go up and left. However, in canvas, it is reversed on the y-axis. You could work with standard coordinates, and convert them to the Canvas coordinates, but this adds some complexity to our code that, frankly, isn't worth the effort. Better to learn the Canvas system.

Radians

An angle is the shape that is formed when two lines intersect. When you think of a 90-degree angle, you understand that two lines have intersected perpendicularly, forming a sharp left or sharp right turn. 180 degrees points you in the opposite direction, and 360 puts you full circle.

Computers, however, think about degrees in terms of radians, so when we begin to draw circles in canvas, you'll also need to think in terms of radians. A complete circle (360 degrees) equals 6.2832 radians. If that's difficult to memorize, it might be better to think of a circle as 2π or 2 pi, where 1 pi equals 3.1416. So working backwards, Math.PI * 2 gives us 6.2832 (a full circle), Math.PI is 3.1416 (a half circle), and Math.PI / 2 is 1.5708 (a quarter circle).

To convert degrees to radians, just remember the formula radians = degrees * Math.PI / 180. And to convert radians to degrees, remember degrees = radians * 180 / Math.PI. Here's a chart to better illustrate the relationship between degrees and radians.

Explanation of the HTML5 Canvas Circle Code

Now that we have a good understanding of circles, we can get back to coding them.

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

var Circle = function(x, y, radius, radians) {
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.radians = radians;

  this.render = function(ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, this.radians, false);
    ctx.fillStyle = '#2793ef';
    ctx.fill();
  }
}

var circle = new Circle(200, 140, 50, Math.PI * 2);
circle.render(ctx);

Lines 1-2: Store an instance of the canvas and canvas context so we can easily reference them later.

Line 4: We define a Circle class, and four important parameters that allow us to size and position our shape.

Lines 5-8: Store the parameters into instance variables. This makes it so each instance of a circle has its own properties that we can define and update without affecting the other circle instances.

Lines 10-15: The render() function is what we invoke to actually draw the shape to the canvas. ctx.beginPath() tells Canvas to begin drawing a path, which we do so with the ctx.arc() method. This method accepts the following parameters, in the order you see them on line 12:

Parameter Description
x The position of the circle on the x-axis
y The position of the circle on the y-axis
r The circle's radius
sAngle The starting angle, in radians, where 0 is the 3 o'clock position, as depicted in the radians chart, above
eAngle The ending angle. The radians we pass in tells the arc how far to draw the circle. Math.PI * 2 produces a full circle, Math.PI produces a half circle, and so on.
counterclockwise An optional argument specifying whether the drawing should be counterclockwise or clockwise

Lines 13-14: Defines fill properties and invokes the ctx.fill() command to fill in the shape.

Lines 18-19: Instantiates the circle and renders it to the canvas.

Conclusion

In this tutorial, we learned about the basic components of a circle and how it is measured. We also learned how to invoke the Canvas API with native JavaScript to render a circle to the screen, and how easy it is to make multiple circles with a Circle class.

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Hire Us for IT and Consulting Services









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Services

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

We Noticed Adblock Running

Because we offer a variety of free programming tools and resources to our visitors, we rely on ad revenue to keep our servers up. Would you consider disabling Adblock for our site and clicking the "Refresh Page" button?

Contact