HTML5 Canvas Tutorial: Circles, Arcs and Curves

In the last two part of the series of this HTML5 tutorial, we have discussed the basics of HTML5 canvas and how to draw shapes like rectangles, lines, triangles, etc with canvas paths. In this article, we will continue with canvas paths and learn to create more interesting and beautiful shapes like circles, arcs and curves.

Before we begin, make sure you have gone through the previous two tutorials on html5 canvas and know how to create paths.

Canvas Basics Tutorial

Canvas Shapes Tutorial

Drawing a circle in canvas

You will remember that for drawing straight lines we use lineTo() method. For creating a circle or an arc in a canvas, we use arc() method.

While creating a straight line in canvas with lineTo() method is pretty simple, the arc() method takes a few extra parameters. As you can understand, circle is a complex shape and to define a circle in canvas coordinates, we require the position of its centre i.e. (x, y) and radius.

The arc and circles are very similar and there is technically no difference in drawing these two on a canvas. For understanding purpose, you may consider arcs as incomplete circle or section of a circle. While circle is a complete round shape, arc can be a part of it. Please see the below diagram for reference.

canvas-arcs

The arc illustrated in this image is a section of the circumference of a circle. To define an arc, we need to take two extra parameters – startAngle and endAngle. These are the two points on the circumference of the imaginary circle to form the arc. As illustrated in the diagram, in html5 canvas, the arc angles starts from the line between the centre and a horizontal line in right direction (i.e. from 3 ‘o clock position of a clock). The last important parameter is the direction of the angle from zero angle line.

The arc() method has the following arguments:

arc(x, y, radius, stratAngle, endAngle, anticlockwise)

We have already discussed about x, y and radius.The arc angles (i.e. startAngle and endAngle) are defined in radians and not in degrees. If you don’t know much about a radian, don’t worry, it’s quite simple. You just need to remember one thing – For creating a full circle (which is 360 degree angle), it takes 2 PI radians. So, with 1 PI, you create an arc of half circle and with 0.5 PI a quarter circle and so on.

The last parameter i.e. anticlockwise is optional and takes Boolean values i.e. true and false. If you set it to true, the arc will be created in anticlockwise direction. Although this parameter is optional, it is advised to explicitly define it either false or true because some of the browsers will throw an error if it is not provided.

Enough theory here, let’s create our first circle.

<html>
<head>
    <script type="application/javascript">
        function drawShape() {
            var canvas = document.getElementById('canvas-tutorial');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
               ctx.beginPath();
                ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);                    
               ctx.fill();
            }
        }
    </script>
    <style type="text/css">
        #canvas-tutorial
        {
            border: 1px solid #000000;
        }
    </style>
</head>
<body onload="drawShape();">
    <canvas id="canvas-tutorial" width="300" height="300">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

canvas-circle

Great, this is nice filled circle. In the code, everything should look familiar to you except this line, which is used for defining the circle

ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);

Here, we are defining the center of the circle as (150, 150). This is 150 pixels in right direction and 150 pixel downwards from top-left corner of the canvas (remember the canvas coordinates). The circle has a radius of 100 pixels. After that we are defining the start angle and end angle of the arc, which is 0 and 2 PI respectively. As you know now that 2 PI is equal to one complete round which defines the full circle. At last we are setting anticlockwise argument to false. Thus from the 0 Angle, circle is created by moving the end angle in clockwise direction. It does not make any difference here, as we are drawing a complete circle. However, if we draw an arc, it will define which side of the 0 angle line the arc will be drawn. Try creating a few circles yourself – some filled and some with just outlines.

Drawing Arcs

Drawing an arc is not different from that of circle. As we have already drawn a circle, we can straight away draw any type of arc. The only difference here is that the difference between start angle and end angle should be less than 2 PI.

Let’s experiment by drawing a few arcs.

<html>
<head>
    <script type="application/javascript">
        function drawShape() {
            var canvas = document.getElementById('canvas-tutorial');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
                ctx.beginPath();
                ctx.arc(150, 150, 100, Math.PI, 1.5 * Math.PI, false);                      
                ctx.stroke();
                ctx.beginPath();
                ctx.arc(150, 150, 80, Math.PI, 1.5 * Math.PI, false);            
                ctx.fill();
                ctx.beginPath();
                ctx.arc(150, 150, 100, -0.25 * Math.PI, 0.75 * Math.PI, false);
                ctx.stroke();
                ctx.beginPath();
                ctx.arc(150, 150, 80, -0.25 * Math.PI, 0.75 * Math.PI, false);
                ctx.fill();
            }
        }
    </script>
    <style type="text/css">
        #canvas-tutorial
        {
            border: 1px solid #000000;
        }
    </style>
</head>
<body onload="drawShape();">
    <canvas id="canvas-tutorial" width="300" height="300">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

arc-with-canvas

And something more interesting

for (var i=1; i&lt;15; i++){
ctx.beginPath();
ctx.arc(150, 150, 10 * i, 0.75 * Math.PI, 1.25 * Math.PI, false);
ctx.stroke();
ctx.beginPath();
ctx.arc(150, 150, 10 * i, -0.25 * Math.PI, 0.25 * Math.PI, false);
ctx.stroke();
}

arcs-with-canvas

Drawing Curves on HTML5 Canvas

Similar to the lines and arcs, Bezier curves are another type of canvas paths. The curves are used to draw complex graphics in canvas. There are two types of Bezier curves – quadratic and cubic. Both of these curves have a start and an end point. The difference between these two is that a quadratic Bezier curve has just one control point while a cubic Bezier curve uses two control points.

240px-Bezier_2_big

240px-Bezier_3_big

If you have already used some vector drawing applications like Inkscape or Illustrator, you may already know how to create shapes with these. Otherwise, you can refer the Wikipedia for complete reference.

The two curves take the following arguments:

quadraticCurveTo(cp1x, cp1y, x, y)

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Just as other paths, we need to first use the moveTo() method to define the starting point of the curve. In the arguments, x and y represents the coordinates of the end point of curve while cp1x and cp1y represents the coordinates of 1st control point. In bezierCurveTo() method, you can find additional cp2x and cp2y arguments for the coordinates of 2nd control point for cubic curve.

canvas quadratic curve canvas cubic curve

Enough Theory – Let’s create curves

<html>
<head>
<script type="application/javascript">
function drawShape() {
var canvas = document.getElementById('canvas-tutorial');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.moveTo(50, 150);
ctx.quadraticCurveTo(20, 70, 150, 50);
ctx.stroke();
ctx.moveTo(100, 250);
ctx.bezierCurveTo(150, 100, 250, 100, 290, 250);
ctx.stroke();
}
}
</script>
<style type="text/css">
#canvas-tutorial
{
border: 1px solid #000000;
}
</style>
</head>
<body onload="drawShape();">
<canvas id="canvas-tutorial" width="300" height="300">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

We have just drawn two curves – one quadratic and other cubic.

curves

While drawing curves can be a lot of fun, it is really challenging because you don’t have visual feedback as you get in vector drawing software. Try creating a few curves on your own to practice.

In these three articles, you have learnt really interesting and useful stuffs. You know about the HTML5 canvas element and how to draw basic shapes and paths. You can now easily draw circles, lines, rectangles and curves. In the next part, we will learn to apply styles and colors to these shapes including radial and linear gradients.

>> Applying colors and styles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>