Learn canvas api in 20 minutes

canvas in 20 minute

Canvas is a html5 api which deal with drawing graphic with javascript. We can use this api for draw graph, 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 above code you can see canvas tag with 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 attribute.

Shapes

Using canvas api we can use lot of shape like rectangle, triangles, lines, arcs and curves But one thing should keep in mind the coordinate system of canvas start from top left corner and 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 list of points by which we can create different different kind 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);

You May Also Like

About the Author: admin