HTML5 Canvas Tutorial: lines & shapes

lines and figures

The canvas includes a number of standard lines and shapes that can be created with Javascript functions: the line, the square or rectangle, the circle, the quadratic curve and bezier curve. The last two are complex names for two types of curve. In this tutorial we will places simple examples of all the lines mentioned and figures on the canvas, then we finally show how by combining the figures you can draw more complex shapes.

1. The line

Drawing a line is conducted using the functions: moveTo(x,y), lineTo(x,y) en stroke().

context.moveTo(x,y);
context.lineTo(x,y);
context.stroke();

Example 1.
The moveTo() method creates the starting point of the canvas context. You can consider it as the positioning of the mouse cursor when drawing a line. The lineTo()) method then draws a line from the context beginning point to the given point. The stroke() method gives the line a color and makes it visible. The default color is black and the default line width is 1px. See image 1.

<!doctype html>
<html>
<head>
<script> 
    function drawLine() 
    {	
        var canvas=document.getElementById("figures");	
        var context=canvas.getContext("2d"); 	
        context.moveTo(25,25);	
        context.lineTo(175,175);	
        context.stroke();	
    }
    window.addEventListener("load", drawLine, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas wth line
Image 1. Canvas element with a line.

Check this example in your browser

1.1 The line width

The thickness of a line we can set using the canvas lineWidth property.

context.lineWidth=[waarde];

Example 1.1. Determining the line width. See image 1.1

<!doctype html>
<html>
<head>
<script> 
    function drawLine() 
    {	
        var canvas=document.getElementById("figures");	
        var context=canvas.getContext("2d"); 	
        context.moveTo(25,25);	
        context.lineTo(175,175);
		 context.lineWidth=7;	
        context.stroke();	
    }
    window.addEventListener("load", drawLine, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas with line with linewidth 7
Image 1.1. Canvas element with on it a line with width=7.

Check this example in your browser

1.2 De line color

The color of a line, we can set using the canvas strokeStyle property.

context.strokeStyle=[waarde];

Example 1.2. Determination of the color of a line. See also image 1.2.

<!doctype html>
<html>
<head>
<script> 
    function drawLine() 
    {	
        var canvas=document.getElementById("figures");	
        var context=canvas.getContext("2d"); 	
        context.moveTo(25,25);	
        context.lineTo(175,175);
		 context.lineWidth=7;
        context.strokeStyle="#f16529";	
        context.stroke();	
    }
    window.addEventListener("load", drawLine, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas with line with color red
Image 1.2. Canvas element with a red line.

Check this example in your browser

1.3 De 'line cap'.

To add a line cap to a HTML5 Canvas line we use the lineCap property.

context.lineCap=[waarde];

When you add a round or square line cap, then the length of the line will increase the size of the value of the line width. For example, if a line is 100 px long, and 20 px thick then with the addition of a round cap or square cap, the length of this line will increase with 20 px. the line will ultimately have a length of 120 px.

Example 1.3. The three types of line caps. See also image 1.3.

<!doctype html>
<html>
<head>
<script> 
    function drawLines() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
     
        // butt line cap (upper line)
        context.beginPath();
        context.moveTo(50,canvas.height/2-75);
        context.lineTo(canvas.width-50,canvas.height/2-75);
        context.lineWidth=20;
        context.strokeStyle="#f16529"; 
        context.lineCap="butt";
        context.stroke();	
     
        // round line cap (middle line)
        context.beginPath();
        context.moveTo(50,canvas.height/2);
        context.lineTo(canvas.width-50,canvas.height/2);
        context.lineWidth=20;
        context.strokeStyle="#f16529"; 
        context.lineCap="round";
        context.stroke();	
     
        // square line cap (bottom line)
        context.beginPath();
        context.moveTo(50,canvas.height/2+75);
        context.lineTo(canvas.width-50,canvas.height/2+75);
        context.lineWidth=20;
        context.strokeStyle="#f16529"; 
        context.lineCap="square";
        context.stroke();	

    }
    window.addEventListener("load", drawLines, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas with red lines and different caps
Image 1.3. Canvas element with lines (top to bottom) with butt, round and square linecaps

Check this example in your browser

2.1 The rectangle

To draw a rectangle (or square), we use the rect() method. The placement of a rectangle in the canvas is done on the basis of the topLeftCornerX and topLeftCornerY parameters. The dimensions are determined by the width and height parameters.

context.rect(topLeftCornerX,topLeftCornerY,width,height);

Example 2.1 Drawing, stroking and filling a rectangle. See also image 2.1

<!doctype html>
<html>
<head>
<script> 
    function drawRectangular() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
           
        var topLeftCornerX = 70;
        var topLeftCornerY = 50;
        var width = 200;
        var height = 100;
     
        context.beginPath();
        context.rect(topLeftCornerX,topLeftCornerY,width,height);
     
        context.fillStyle="#f16529";
        context.fill();
        context.lineWidth=7;
        context.strokeStyle="black"; 
        context.stroke();	
    }
    window.addEventListener("load", drawRectangular, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas with rectangular
2.1 Image Canvas element with rectangle with red fill and black stroke.

Check this example in your browser

2.2 The rectangle with rounded corners

For drawing a rectangle (or square) with rounded corners, there is no direct method available in the HTML5 Canvas API. But we can however use a trick to simulate rounded corners. The code below shows how this is done:

Example 2.2 Drawing a rectangle with rounded corners. See also image 2.2

<!doctype html>
<html>
<head>
<script> 
    function drawRoundedRectangular(){
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
        var topLeftCornerX = 70;
        var topLeftCornerY = 50;
        var rectWidth = 200;
        var rectHeight = 100;
        var cornerRadius = 13;
        context.lineJoin = "round";
        context.lineWidth = cornerRadius;
        context.strokeStyle = "black";
        context.fillStyle="#f16529";
        context.fillRect(topLeftCornerX+(cornerRadius/2), topLeftCornerY+
                               (cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
        context.strokeRect(topLeftCornerX+(cornerRadius/2), topLeftCornerY+
                               (cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
    };
 window.addEventListener("load", drawRoundedRectangular, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas rectangle with rounded corners
Image 2.2. Canvas element with rectangle with rounded corners

Check this example in your browser

3. The circle

To draw a circle, we can use the arc () method, in which we set the starting angle to 0 and the target angle 2 * PI. This is the angle in radians (an arithmetic unit for the expression of angles), which corresponds to an angle of 360 degrees. The parameters centerX and centerY indicate the coordinates of the center of the circle.

context.arc(centerX,centerY,radius,0,2*Math.PI,false);;

Example 3. Drawing, stroking and filling a circle. See image 3.

<!doctype html>
<html>
<head>
<script> 
    function drawCircle() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
           
        var centerX = 175;
        var centerY = 100;
        var radius = 70;
     
        context.beginPath();		
        context.arc(centerX,centerY,radius,0, 2*Math.PI,false);
     
        context.fillStyle="#f16529";
        context.fill();
        context.lineWidth=7;
        context.strokeStyle="black"; 
        context.stroke();
    }
    window.addEventListener("load", drawCircle, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas with circle
Image 3. Canvas element with a circle with red fill and black stroke

Check this example in your browser

3.1. The partial circle

To draw a semicircle we set the target angle parameter to Math.PI (half of 2 * Math.PI). To close the outline, we finally add the rule context.closePath(). The code for the semicircle then will look as follows:

<!doctype html>
<html>
<head>
<script> 
    function drawCircle() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
           
        var centerX = 175;
        var centerY = 100;
        var radius = 70;
     
        context.beginPath();		
        context.arc(centerX,centerY,radius,0, Math.PI,false);
        context.closePath();
     
        context.fillStyle="#f16529";
        context.fill();
        context.lineWidth=7;
        context.strokeStyle="black"; 
        context.stroke();
    }
    window.addEventListener("load", drawCircle, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
 Canvas element with a half a circle with a red fill and black stroke.
Image 3.1. Canvas element with a half a circle with a red fill and black stroke.

Check this example in your browser

3.2 The ellipse

To draw an ellipse, we can make use of the arc() method in combination with the scale() method. (more about the scale() method you'll find in the tutorial "Tutorial Transformations: scaling"). We can do this through the following sequential steps:

  1. saving the state of the context with the save() method;
  2. stretching the canvas context with scale ();
  3. drawing a circle with arc();
  4. restoring the stored state of the context with restore();
  5. styling (add a fill and stroke) with fill() and stroke().
<!doctype html>
<html>
<head>
<title>The Canvas element with ellipse</title>
<script> 
function drawElips(){
    var canvas = document.getElementById("figures");
    var context = canvas.getContext("2d");
 
    context.save(); // save state of context
    var middelpuntX = 0;
    var middelpuntY = 0;
    var straal = 50;
 
    context.translate(canvas.width / 2, canvas.height / 2);
    context.scale(3,1);
 
    context.beginPath();
    context.arc(middelpuntX, middelpuntY, straal, 0, 2 * Math.PI, false);
 
    context.restore(); // restore context to original state
    context.fillStyle = "#f16529";
    context.fill();
    context.lineWidth = 7;
    context.strokeStyle = "black";
    context.stroke();
};
    window.addEventListener("load", drawElips, true);
</script>
</head>
<body>	
	<canvas id="figures" style="border: 1px solid;" width="350" height="200"></canvas>
</body>
</html>
Canvas element with ellipse with red fill and black stroke.
Image 3.2. Canvas element with ellipse with red fill and black stroke.

Check this example in your browser

4. The quadratic curve

For drawing of a random, non-standard, figure we can make use of the quadraticCurveTo() method. Quadratic curves are defined by three points: a context point, a control point and an ending point:

context.quadraticCurveTo(controlX, controlY, endX, endY);
Example 4. Drawing a quadratic curve. See image 4.
<!doctype html>
<html>
<head>
<script> 
    function drawQuadraticCurve() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
           
        context.moveTo(50,25);
        context.quadraticCurveTo(175, 300, 300, 25);
        context.lineWidth=7;
        context.strokeStyle="black"; 
        context.stroke();
    }
    window.addEventListener("load", drawQuadraticCurve, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas element with quadratic curve
Image 4. Canvas element with quadratic curve

In the figure below, we see how a control point controls the curvature of the quadratic curve through two imaginary tangents which are associated with the context point and the end point. The context is defined by the moveTo() method. By moving the context point further away from the the control point and the end point we get a more elongated curve.

Explanation Canvas with quadratic curve

Check this example in your browser

5. The bezier curve

If we want more control over drawing a curve, we can use the bezierCurveTo() method instead of the quadraticCurveTo() method. This makes it possible to draw more complex lines. Bezier curves are defined by four points: a context point, two control points and an ending point. Unlike in the quadratic curves, with bezier curves, there is no question of just one control point, but two control points.

context.bezierCurveTo(controlX1, controlY1, controlX2, controlY2, endX, endY);
Example 5. Drawing a bezier curve. See also image 5.
<!doctype html>
<html>
<head>
<script> 
    function drawbezierCurve() 
    {	
        var canvas=document.getElementById("figures");
        var context=canvas.getContext("2d");
           
        	context.moveTo(100,25);
           context.bezierCurveTo(-100, 200, 200, 200, 300, 25);
           context.lineWidth=7;
           context.strokeStyle="black"; 
           context.stroke();	
}

    }
    window.addEventListener("load", drawbezierCurve, true); 
</script>
</head>
<body>	
<canvas id="figures" style="border: 1px solid;" width="350" height="200">
</canvas>
</body>
</html>
Canvas element with bezier curve
Image 5. Canvas element with bezier curve

In the figure below, we see how a bezier curve is defined by the context point, two control points and an ending point. The first part of the curve is controlled by an imaginary tangent in the context point to the first control point. The second part of the curve is determined by an imaginary line running from the first to the second control point. The third part of the curve is determined by an imaginary tangent line at the endpoint to the second control point.

Uitleg Canvas met quadratic curve

Check this example in your browser

Next tutorial

Leave a comment