## The canvas drawing API

The canvas drawing API gives us the ability to draw things such as shapes and fills using JavaScript. It exposes a rich set of functionality through a small number of methods.

### The canvas context

The canvas context allows us to access the canvas drawing API, which is just a collection of properties and methods of that object.

We access it as follows:

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


### Drawing lines and curves

Here are a few essential properties and methods of the canvas context we shall be using for drawing basic shapes using lines and curves:

• strokeStyle – this property specifies the line color. Its default value is ‘#000000’ (black).
• lineWidth – this property specifies the line thickness in pixels. Its default value is 1.
• beginPath() – this method resets the current path. A path is a collection of subpaths, whereby each subpath is a set of points connected by straight or curved lines.
• closePath() – this method closes the current subpath and starts a new subpath from the end of the closed subpath.
• moveTo(x, y) – this method moves the cursor to a location (x, y) without drawing anything.
• lineTo(x, y) – this method draws a straight line from the current cursor location to a new location (x, y).
• arc(x, y, radius, startAngle, endAngle, anticlockwise) – this method adds creates an arc on the path with center (x, y), specified radius, starting and ending angles in radians. The anticlockwise parameter is a boolean variable which if true, the arc is drawn in an anticlockwise direction and if false, the arc is drawn in a clockwise direction.
• rect(x, y, w, h) – this method creates a new closed rectangular subpath with the upper-left corner at (x, y), width w and height h.
• stroke() – this method renders the current subpath using the current stroke styles.
• strokeRect(x, y, w, h) – this method is a combination of the rect(x, y, w, h) and stroke() methods used to render an outline of the specified rectangle.

#### Drawing a line

Now let us see examples of how we use the above mentioned methods. First create your project folder on your P.C. and name it whatever you want. Inside the project folder, create two files, the first one named index.html and the second one name script.js.

The index.html will hold our canvas element and a reference to our script.js file, so write the following code in it:

<!DOCTYPE html>

<html>

<style type="text/css">
#canvas1{
background-color:silver;
}
</style>

<body>

<canvas id="canvas1" width="600" height="480">
<!-- Insert fallback content here -->
</canvas>

<script type="text/javascript" src="script.js"></script>

</body>
</html>


Now put the following code in the script.js file:

//first get the canvas and its context
var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

//set the strokeStyle colour
context.strokeStyle = '#230387';

//set the line width
context.lineWidth = 4;

context.beginPath();

//move your pen to this point without drawing anything
context.moveTo(50, 10);

//set up a line from the above mentioned point to this point
context.lineTo(250, 400);

//draw the line
context.stroke();


This way we have separated the user interface from the logic. The comments in the code above explains what each line is doing. Please take note that the line will be drawn after you call the context.stroke().

Let me explain the whole code in layman’s terms. Lets say you want to draw a line on paper, you follow the following steps:

• choose your paper → var canvas = document.getElementById("canvas1"); var context = canvas.getContext('2d');
• choose the pencil colour and size → context.strokeStyle = '#230387'; context.lineWidth = 4;
• hold your pencil → context.beginPath();
• choose a point where you want your line to begin → context.moveTo(50, 10);
• choose a point where you want your line to end → context.lineTo(250, 400);
• now draw the line by connecting the two points → context.stroke();

Now that we understand what the code does, lets run it. Make sure the two files we created above are in the same folder and then launch the index.html using your favourite browser.

Output #### Drawing a triangle

When drawing a triangle in canvas, the first important thing id to know it vertices (corner points). Mark the three vertices on canvas, then join the points with straight lines.

script.js

//first get the canvas and its context
var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

//set the strokeStyle colour
context.strokeStyle = '#230387';

//set the line width
context.lineWidth = 4;

context.beginPath() ;

//move your pen to this point without drawing anything
context.moveTo(20, 30);

//set up a line from the above mentioned point to this point
context.lineTo(300, 120);

//set up another line to this point
context.lineTo(200, 320);

//close the shape by joining the current point with the first point
context.closePath();

//draw the lines
context.stroke();



Output You can also fill the triangle by calling the context.fill() method as follows:

script.js

var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

context.strokeStyle = '#230387';
context.lineWidth = 4;
context.beginPath() ;
context.moveTo(20, 30);
context.lineTo(300, 120);
context.lineTo(200, 320);
context.closePath();

//fill the shape with default colour (black)
context.fill();

context.stroke();


Output #### Drawing a rectangle

Now lets draw a rectangle with top left corner at point (20,30), width 100, height 200.

script.js

var canvas = document.getElementById("canvas1");
var context = canvas.getContext('2d');

context.strokeStyle = '#230387';
context.lineWidth = 4;

//rectangle from point (20,30), width 100, height 200
context.rect(20,30, 100, 200)

context.stroke();


Output
{"ft_lang_label":"__label__en","ft_lang_prob":0.7153695,"math_prob":0.6981641,"size":5854,"snap":"2022-27-2022-33","text_gpt3_token_len":1328,"char_repetition_ratio":0.15726496,"word_repetition_ratio":0.14972067,"special_character_ratio":0.26375127,"punctuation_ratio":0.17060368,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9703138,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-07-01T04:32:04Z\",\"WARC-Record-ID\":\"<urn:uuid:a9beb505-cde9-4fa3-8de7-0a9af01a7462>\",\"Content-Length\":\"69831\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e2b049b4-ccc5-44ba-a83b-1bc7a7cec826>\",\"WARC-Concurrent-To\":\"<urn:uuid:7e52d260-5656-4617-8c8e-7d98396e348b>\",\"WARC-IP-Address\":\"149.255.62.4\",\"WARC-Target-URI\":\"https://sytech.co.zw/html5-canvas-tutorial/canvas-drawing-api/\",\"WARC-Payload-Digest\":\"sha1:IZDWVQLENFQJ7BZ3OV66DDFHUSESUU6Z\",\"WARC-Block-Digest\":\"sha1:CXFCTBACQLE4FROVBFGAAFYNJSZDWFAA\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656103920118.49_warc_CC-MAIN-20220701034437-20220701064437-00296.warc.gz\"}"}