{ Introduction to Canvas. }

Objectives:

By the end of this chapter, you should be able to:

  • Describe what a canvas element is and what it's used for
  • Setup a canvas element and describe the coordinate system

Canvas Introduction

A canvas is an html element that allows the developer to draw shapes, text, etc. It was originally introduced by Apple as an attempt to make the web more dynamic.

Here is a basic canvas tag:

<canvas height="200" width="200">
    This text is shown to the user if the browser does not support canvas
</canvas>

Your imagination is the only thing holding you back with the canvas element. This tuts plus article, 21 Ridiculously Impressive HTML5 Canvas Experiments, gives some really cool examples of what is possible.

We have much more modest goals for this lesson. We are going to go over the basic canvas setup, drawing a few shapes, and then make our shapes move.

Canvas Setup

To create your first canvas element, let's start with this html:

<!DOCTYPE html>
<html>
<head>
  <title>Canvas Intro</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="my-canvas"></canvas>
</body>
</html>

And this code for style.css:

#my-canvas {
    background-color: blue;
    height: 400px;
    width: 400px;
}

If you open up your html page in a browser, you should see a blue html canvas on the screen! Here's what that looks like

Now, open up your javascript console, and get the canvas element by doing the following:

var canvas = document.getElementById("my-canvas");

Next, we'll start adding elements to the canvas, but first we need to understand the x and y coordinate system.

Coordinates System in Canvas

In the canvas coordinate system, the x coordinate grows from the left side of the element to the right and the y coordinate grows from the top of the canvas to the bottom.

This coordinate system can seem not very intuitive to some people since they are used to graphs from math where the y value gets larger from bottom to top, but once you get the hang of it, you'll be fine.

We also want to make sure that the width and height of our canvas is the same as the width and height on the page. Try doing the following in the console:

var canvas = document.getElementById("my-canvas");
console.log("width: ", canvas.width, "height: ", canvas.height);

The above code should return a width of 300 and a height of 150, but our canvas has a different dimension on the page. In fact, 300 and 150 are the default values of width and height for a canvas element. The difference of the canvas dimensions and the real world pixel dimensions will lead to confusion and problems, so the easiest thing to do is update the canvas size to the values from our style:

var canvas = document.getElementById("my-canvas");
canvas.width = canvas.scrollWidth;
canvas.height = canvas.scrollHeight;

When you're ready, move on to Canvas Continued

Continue

Creative Commons License