Broad Network


Drawing Straight Lines in an HTML Canvas

HTML Canvas 2D Context – Part 2

Foreword: In this part of the series, I explain how to cause DOM to draw straight lines in the html canvas element.

By: Chrysanthus Date Published: 16 Apr 2016

Introduction

This is part 2 of my series, HTML Canvas 2D Context. In this part of the series, I explain how to cause DOM to draw straight lines in the html canvas element. I assume you have read the previous part of the series, because this is a continuation. The context object has properties and methods that are used to draw lines. So, in this part of the series, I explain how to use these properties and methods. Now, teaching drawing in computing is not a straightforward issue, so you must try all the code samples in this tutorial in order to appreciate the subject (series).

Path and Subpath
A line whether straight or not is considered as a path. This path is considered to consist of portions called subpaths (sub-paths).

The canvas Object
The canvas object is a DOM object (code) that draws on the canvas element.

The Context
The context represents a drawing. You can have more than one drawing in the canvas, with each having its own context (context is also a software object).

The beginPath() Method
The context beginPath() method begins a subpath to which other subpaths can be added. This method does not start the path (see below).

The moveTo(x,y) Method
The context beginPath() method does not create the starting point (dot) of the path. It begins the drawing scheme, and not the path. The moveTo(x,y) method moves the context to the starting point (dot) at the coordinates, (x,y). The moveTo(x,y) method starts the path at position, (x,y). Remember, x is the horizontal distance measured from the left edge of the canvas, while y is the vertical distance measured from the top edge of the canvas.

The lineWidth Property
The context lineWidth property gives the width of the line.

The strokeStyle Property
The context strokeStyle property gives the color or style of the line.

The lineTo(x,y) Method
The context lineTo(x,y) method draws a straight line from the last point in the subpath to the new point (x,y).

The stroke() Method
The context stroke() method gives the path its looks (color).

Drawing a Straight Line
To draw a straight line you need a context. After that you need to use all the above properties and methods. You obtain a context from a DOM canvas object. You obtain the canvas object from the html canvas element itself. Read and try the following code, noting the order of the statements, especially the positions of the beginPath() and stroke() methods (click the button to see the line).

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
        <script type="text/ECMAScript">
            function drawLine()
            {
                cv = document.getElementById('C1');
                if (cv.getContext)
                    {
                        cntxt = cv.getContext('2d');

                        cntxt.beginPath();
                        cntxt.lineWidth = 6;
                        cntxt.strokeStyle = "green";
                        cntxt.moveTo(40,170);
                        cntxt.lineTo(60,90);
                        cntxt.stroke();
                    }  
            }

</script>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
        Your browser does not support the canvas element! So you cannot see the chart. Please upgrade your browser.
    </canvas>
    <button type="button" onclick="drawLine()">Click</button>

</body>
</html>

Drawing more than one Thing in the Same Canvas
You can have more than one drawing (line) in the same canvas. Each drawing may have its own context. Read and try the following code that draws two different lines using two different contexts:

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
        Your browser does not support the canvas element! So you cannot see the chart. Please upgrade your browser.
    </canvas>

    <script type="text/ECMAScript">
        cv = document.getElementById('C1');
        if (cv.getContext)
            {
                contextA = cv.getContext('2d');
                contextA.beginPath();
                contextA.lineWidth = 6;
                contextA.strokeStyle = "green";
                contextA.moveTo(40,170);
                contextA.lineTo(60,90);
                contextA.stroke();

                contextB = cv.getContext('2d');
                contextB.beginPath();
                contextB.lineWidth = 6;
                contextB.strokeStyle = "green";
                contextB.moveTo(140,90);
                contextB.lineTo(160,170);
                contextB.stroke();
            }  

    </script>

</body>
</html>

The lineCap Property
The context lineCap property determines the shape of the ending of a line. There are three possible values, which are, butt, round, and square. The best way to appreciate these is to try a code. In the following code the first line has butt endings; the second line has round endings; the third line has square endings.

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
        Your browser does not support the canvas element! So you cannot see the chart. Please upgrade your browser.
    </canvas>

    <script type="text/ECMAScript">
        cv = document.getElementById('C1');
        if (cv.getContext)
            {
                cntxtA = cv.getContext('2d');
                cntxtA.beginPath();
                cntxtA.lineWidth = 15;
                cntxtA.lineCap = "butt";
                cntxtA.strokeStyle = "blue";
                cntxtA.moveTo(40,90);
                cntxtA.lineTo(140,90);
                cntxtA.stroke();

                cntxtB = cv.getContext('2d');
                cntxtB.beginPath();
                cntxtB.lineWidth = 15;
                cntxtB.lineCap = "round";
                cntxtB.strokeStyle = "blue";
                cntxtB.moveTo(40,130);
                cntxtB.lineTo(140,130);
                cntxtB.stroke();

                cntxtC = cv.getContext('2d');
                cntxtC.beginPath();
                cntxtC.lineWidth = 15;
                cntxtC.lineCap = "square";
                cntxtC.strokeStyle = "blue";
                cntxtC.moveTo(40,170);
                cntxtC.lineTo(140,170);
                cntxtC.stroke();
            }  

    </script>

</body>
</html>

So the “butt” value of the lineCap shortens the endings of the line, making them flat. The  “round” property rounds the endings by pushing backward the corners of the line. The “square” property allows flat endings for the line. The lineCap property should be typed before the stroke() method in the code.

The lineJoin Property
Two connecting lines (subpaths) of a context can be joined in three different ways. These three different ways correspond to three different values that can be assigned to the context lineJoin property. The three possible values are: miter, bevel and round. Miter is the default. The best way to appreciate these values is to try them out. Read and try the following code:

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
    </canvas>

    <script type="text/ECMAScript">
        cv = document.getElementById('C1');
        if (cv.getContext)
            {
                cntxt = cv.getContext('2d');
                cntxt.beginPath();
                cntxt.lineWidth = 6;
                cntxt.strokeStyle = "blue";
                cntxt.lineJoin = "miter";
                cntxt.moveTo(40,120);
                cntxt.lineTo(120,30);
                cntxt.lineTo(200,120);
                cntxt.stroke();

              
            }  

    </script>

</body>
</html>

Now change the value of the lineJoin property to "bevel". Next change the value of the lineJoin property to "round". So, the miter value has a sharp join, the bevel value has a flat join and the round value has a round join. In the absence of the lineJoin property, you have the miter value, the default.

Closing a Path
A path is made up of subpaths. In a drawing, the path may be opened or form a closed loop. The context closePath() method closes a path. In the following code, a line goes up, then comes down in a different direction and the closePath() method closes the path to form a triangle. Read and try the code:

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
        Your browser does not support the canvas element! So you cannot see the chart. Please upgrade your browser.
    </canvas>

    <script type="text/ECMAScript">
        cv = document.getElementById('C1');
        if (cv.getContext)
            {
                cntxt = cv.getContext('2d');
                cntxt.beginPath();
                cntxt.lineWidth = 6;
                cntxt.strokeStyle = "green";
                cntxt.moveTo(40,90);
                cntxt.lineTo(140,20);
                cntxt.lineTo(200,150);
                cntxt.closePath();
                cntxt.stroke();
            }  

    </script>

</body>
</html>

The closePath() method is typed before the stroke() method.

Filling a Closed Path with Color
You can fill the inside of a closed path with a color. To achieve this, you need a property of the context object called, fillStyle and a method of the context object called, fill(). You assign the color to the fillStyle property and then use the fill() method to fill the inside of the closed path. The property and the method are typed just before the stroke() method, after the closure (closePath()). Read and try the following code:

<!DOCTYPE HTML>
<html>
<head>
    <title>Illustration</title>
</head>
<body>
    <canvas id="C1" width="400" height="300" style="float:right;border:2px solid red">
    </canvas>

    <script type="text/ECMAScript">
        cv = document.getElementById('C1');
        if (cv.getContext)
            {
                cntxt = cv.getContext('2d');
                cntxt.beginPath();
                cntxt.lineWidth = 6;
                cntxt.strokeStyle = "green";
                cntxt.moveTo(40,90);
                cntxt.lineTo(140,20);
                cntxt.lineTo(200,150);
                cntxt.closePath();
                cntxt.fillStyle = "yellow";
                cntxt.fill();
                cntxt.stroke();              
            }  

    </script>

</body>
</html>

Time to take a break. We stop here and continue in the next part of the series.

Chrys

Related Links

DOM Basics for HTML
DOM Event Basics for HTML
HTML Text and Other Elements in DOM
HTML Grouping and Sectioning Content Elements in DOM
DOM and HTML Embedded Content
HTML Canvas 2D Context
More Related Links
PurePerl MySQL API
Major in Website Design
Web Development Course
Producing a Pure Perl Library

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message