Canvas Drawing API

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>

<head>

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



</head>

<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;

//begin your path
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



Canvas drawing api



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;

//begin your path
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



Canvas


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



Canvas



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



canvas rect