Learn Canvas API in 20 Minutes

Canvas is a html5 API which deals with drawing graphics with javascript. We can use this API to draw graphs, photo editing and animation. So in this tutorial, we will cover how to deal with 2D graphics.

Prerequisite

  1. Text editor
  2. Browser (Chrome)

Get Started


<!DOCTYPE html>
<html lang="en">
<head>
 <style>
canvas { border: 1px solid black;}
</style>
</head>
<body>
<canvas id="page"></canvas>
<script>
 (function () {
    var canvas, ctx;
    function Main() {
        canvas = document.getElementById('page');
        ctx = canvas.getContext('2d');
        ctx.fillStyle = 'rgb(300, 0, 0)';
        ctx.fillRect(20, 20, 40, 40);
        ctx.fillStyle = 'rgba(0, 0, 300, 0.5)';
        ctx.fillRect(30, 30, 40, 40);
    }
    window.addEventListener("load", Main, false);
}());
</script>
</body>
</html>

In the above code, you can see the canvas tag with the id attribute but we should keep in mind the default height and width are 300px × 150px (width × height). We can change using height and width attributes.

Shapes

Using canvas API we can use a lot of shapes like rectangles, triangles, lines, arcs and curves But one thing that should keep in mind the coordinate system of canvas start from the top left corner and the left to right is x coordinate and top to bottom is y coordinate.

Rectangles

To create rectangles we can use –

  1. fillRect(x, y, width, height) – Draws a filled rectangle.
  2. strokeRect(x, y, width, height) – Draws a rectangular outline.
  3. clearRect(x, y, width, height) – Clears the rectangular area

ctx.fillRect(20, 20, 100, 100);
ctx.clearRect(30, 30, 60, 60);
ctx.strokeRect(40, 40, 40, 40);

Paths

A path is a list of points by which we can create different kinds of shapes so for that we can use –

  1. beginPath() – Creates a new path
  2. closePath() – Close the path and create new sub path
  3. stroke() – Draw shape using stroke
  4. fill() – Draw solid shape

ctx.fillStyle = 'rgb(100, 50, 50)';
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();

Lines

For line we can use

  1. lineTo(x, y) – drawa a line

// Triangle
ctx.fillStyle = 'rgb(100, 50, 50)';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(100, 25);
ctx.lineTo(20, 100);
ctx.fill();

Drawing text

We have –

  1. fillText(text, x, y [, maxWidth]) – text filled using current fillstytle
  2. strokeText(text, x, y [, maxWidth]) – text filled using strokes

// without stroke 
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);

// with stroke 
ctx.font = '48px serif';
ctx.strokeText('Hello world', 10, 50);

About the Author: Pankaj Bisht