Level-Up Coding

Level 3: You can draw on a web page with Javascript and HTML Canvas.

The HTML <canvas> is a special element that allows you to draw on it by writing drawing commands in Javascript. Some of the commands are to draw rectangles, circles, text, and images.


An example with HTML canvas

Below is an example of an HTML page with a canvas element and some Javascript commands to draw on it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Page With Canvas</title>
</head>

<body>
    <h1>This page shows a canvas element</h1>
    <canvas id="myCanvas" width="600" height="400"></canvas>
    <img id="shipImage" style="display:none;" src="shipImage.png"></img>

    <script>
    // The window.onload function will run when the page first loads
    window.onload = function() 
    {
        // First, Get a reference to the canvas, looking it up by name
        var canvas = document.getElementById("myCanvas");

        // Next, get a 2d "graphics context" for the canvas.
        var drawing = canvas.getContext("2d");

        // Draw a background rectangle
        var w = canvas.width;            // get the width of the canvas
        var h = canvas.height;           // get the height of the canvas
        drawing.fillStyle = "#BBBBFF";   // light blue fill color
        drawing.fillRect(0,0,w,h);       // fill the canvas with light blue
        drawing.strokeRect(0,0,w,h);     // draw a black border

        // Get the ship image and draw it
        var shipImage = document.getElementById("shipImage");
        drawing.drawImage(shipImage, 10, 10);
        drawing.drawImage(shipImage, 300, 10, 100, 100);
    }
    </script> 
</body>
</html>

The HTML part

The first part of the code gives the page layout in HTML. In other words, it describes what things will be on the page and where they will go. The page has a <canvas> element, and also an image that is not displayed. You can see that it will not be displayed, because it has the property style="display:none;". However, it is included so that it can be used later to draw on the canvas.

    <h1>This page shows a canvas element</h1>
    <canvas id="myCanvas" width="600" height="400"></canvas>
    <img id="shipImage" style="display:none;" src="ship.png"></img>

One thing to notice about the <canvas> element is that it has width and height properties. This tells the computer how big to draw the canvas on the screen. In this case, the canvas will be 600 pixels wide, and 400 pixels high. The term pixel is short for “pixel element”. Images in the computer are made of a grid of tiny colored dots. Each pixel is one dot of the image, so the canvas has 600 x 400 = 240,000 total dots.


window.onload

Recall that the Javascript code of the page is given in a <script> element. The line window.onload = function() defines a function that will run as soon as all of the content has loaded. In other words, the browser waits for all the HTML elements, images, and other content to load first, and then calls the function. By putting our code in the onload function, we can make sure that it runs after the page has loaded all of the images that it will use.

As mentioned in a previous lesson, when the function runs, it will execute the code in the function one line at a time, from top to bottom. You can think of this as the starting point for the Javascript program.


The Graphics Context

The goal of the example Javascript program is to create a drawing on the canvas. In order to do this, the program needs the graphics context of the canvas. Imagine that the canvas is a piece of paper. Getting the grahics context is sort like deciding which piece of paper you want to draw on. When the code draws to the graphics context of the canvas, the drawing will show up on it. To get this context, first, we get a reference to the canvas itself, and then get its graphics context. The code does this with the following lines:

    // First, Get a reference to the canvas, looking it up by name
    var canvas = document.getElementById("myCanvas");

    // Next, get a 2d "graphics context" for the canvas.
    var drawing = canvas.getContext("2d");

The dot operator

You may have noticed that Javascript code uses a dot (.) sometimes. The code above has document.getContext("2d");, and the code from a previous level had c.innerHTML. In both of these cases, the dot tells the computer to look at something inside something else. getContext is a function inside the document variable, and innerHTML is a property inside the variable c.


Clearing the canvas by drawing a rectangle

After getting the graphics context, the code can actually draw something. The first thing that it does is to set the fillStyle of the drawing context.

fillRect colors in a rectangle covering the whole canvas. Then, it draws a border around the whole canvas using the strokeRect command.

    // Draw a background rectangle
    var w = canvas.width;            // get the width of the canvas
    var h = canvas.height;           // get the height of the canvas
    drawing.fillStyle = "#BBBBFF";   // light blue fill color
    drawing.fillRect(0,0,w,h);       // fill the canvas with light blue
    drawing.strokeRect(0,0,w,h);     // draw a black border

Hex Colors

You may have noticed that it said the color for the rectangle was light blue. But how do we get light blue out of “#BBBBFF”?

In Javascript you can create colors using hexadecimal notation (or just hex for short). Hexadecimal is a numbering system that has 16 digits rather than the 10 that you are used to. The digits are 0123456789ABCDEF. In this scheme, A means 10, and F means 15.

To make a color, you start with a # sign, and then use two hex digits to indicate how much red, green, and blue you want in the color. 00 means that you don’t want any of that color, 88 means that you want about half of that color, and FF means that you want as much as possible.

With the hex system you can literally specify millions of different colors. Here are some example colors given in hex format:

    #000000   black
    #FF0000   red
    #00FF00   green
    #0000FF   blue
    #FFFF00   yellow
    #888888   gray
    #FF8800   orange

There are also some web pages that will allow you to pick colors and see their hex values. One of these is (https://www.google.com/#q=hex+color+picker).


Pixel coordinates

In order to draw a rectangle, we have to tell the computer where it should be on the canvas, and how big it should be. We use pixel coordinates to do this. For the canvas, coordinates are two numbers that tell the computer where a point is located. This is like a number line, except there are you need two numbers instead of one.

The first number is called the x coordinate. It tells how far a point is from the left edge of the canvas. The second coordinate is called the y coordinate. It tells how far the point is from the top of the image, with positive numbers going down. Based on this, the top left corner of the canvas is at coordinates (0,0), and (w,h) is the bottom right of the canvas, where w is the width of the canvas, and h is its height. The figure below shows this.


Drawing a rectangle

To draw a rectangle, we give the computer the coordinates of the top left corner followed by the width and height of the rectangle. Since the canvas was defined to be 600 pixels wide and 400 pixels high, the line drawing.fillRect(0,0, 600,400); fills the entire canvas with the current fill color. The line strokeRect(0,0, 600,400); only draws the outline of the rectangle.


Drawing images

The final thing that the program does is to draw an image on the canvas. To draw an image, it first makes an <img> tag in the HTML part of the page to include the image. Then it sets the style property to "display:none;":

    <img id="shipImage" style="display:none;" src="shipImage.png"></img>

Next, add Javascript code to draw the image to the canvas. In the Javascript code, get a reference to the image element and then draw it on the canvas. Two numbers passed to the drawImage function are the pixel coordinates of the top left corner of the images.

    // Get the ship image and draw it
    var shipImage = document.getElementById("shipImage");
    drawing.drawImage(shipImage, 10, 10);

To change the size of the image, you can add add two more numbers for the width and height. The line below draws the shipImage once again, but this time with a width and height of 100 pixels.

    drawing.drawImage(shipImage, 300, 10, 100, 100);

The diagram below shows how the two ships will be drawn on the canvas:


Drawing text on the canvas

You can draw text directly on the canvas. Before drawing some text, you can set the text size and font, color, and alignment. The code below writes the word “Javascript” in dark blue in the center of the canvas using the Arial font.

    drawing.font = "30px Arial";
    drawing.fillStyle = "#000088";
    drawing.textAlign = "center";
    drawing.fillText("Javascript", canvas.width/2, canvas.height/2); 

Errors and Debugging

Programming languages like HTML and Javascript are not very smart. Tiny errors throw them off. If things are misspelled, or even mis-capitalized, they don’t understand what you mean. For example, this line of code draws the robot image on the canvas:

    drawing.drawImage(shipImage, 450, 100);

But this line of code is an error:

    drawing.drawImage(shipImage 450, 100);

Can you spot the difference? It’s just that a comma is missing between shipImage and 450. That one little mistake broke the program!

Sometimes it can be hard to find out what is going wrong with a program. One helpful feature many browsers include is called the web console. It is a special place in the browswer that shows errors that happen on a web page. You can also print things to the console using the command console.log:

    console.log("message");

Each browser handles the web console a bit differently. Here is how to open it in some of the major browsers:


Terms


Exercise

  1. Make a new folder on your computer for this assignment.

  2. Copy the page at the top of the assignment to a text editor. Save the page as a .html file in the folder you made, and then open it in a web browser.

  3. Copy the images (shipImage.png) and (robotImage.png) to the same folder.

  4. Open the web console in your browser.

  5. Draw a small rectangle somewhere on the page. Think about how you will set the color, coordinates, width, and height of the rectangle.

  6. Add an <img> tag for the robotImage.png image. Give this tag an id, and also set the style property to "display:none;".

  7. Display several robots on the screen with different positions and sizes.