Lesson 1

First Steps with the HTML5 Canvas

Let's dive in and start drawing with the canvas right now. We will do this by executing javascript commands in the browser, so let's open the javascript console.

Google Chrome is the browser I recommend, especially for this tutorial since we will be making use of Chrome's developer tools.

To show were we are going, just copy and paste the following sequence of commands into the console, hit enter, and click on the output.

var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0,0,50,50);
ctx.fillStyle = "green";
ctx.fillRect(0,50,50,50);
ctx.fillStyle = "blue";
ctx.fillRect(50,0,50,50);
ctx.fillStyle = "yellow";
ctx.fillRect(50,50,50,50);
canvas.toDataURL();

Clicking the output link should reveal a 100x100 image made up of 4 colored squares.

Now let's run the same series of commands one at a time, and understand how we actually made this image.

In the console let make a new 100 x 100 canvas.

var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;

To draw on a canvas, we always need to get the CanvasRenderingContext2D of the canvas, and we can do so with the following code.

var ctx = canvas.getContext("2d");

Now we can draw on the canvas! ctx, our CanvasRenderingContext2D, is the machine which draws on the canvas. So let's command it to draw. How about a simple red rectangle.

ctx.fillStyle = "red";
ctx.fillRect(0,0,50,50);

At any time, we can print the image data on our canvas in the console with the command:

canvas.toDataURL();

Which will print the image data as a link which you can click to view.

Now execute the code to draw other other 3 squares:

ctx.fillStyle = "green";
ctx.fillRect(0,50,50,50);
ctx.fillStyle = "blue";
ctx.fillRect(50,0,50,50);
ctx.fillStyle = "yellow";
ctx.fillRect(50,50,50,50);

and our canvas is done, with 4 colored squares drawn to it. We can view our final image in the same way we have been viewing the canvas all along:

canvas.toDataURL();

If you are new to canvas and/or javascript and you are confused, you are supposed to be! If you are reading this, then presumably you made it through the tutorial, and you are well on your way to learning to work with canvas. There's nothing holding you back.



`