JAVASCRIPT & the HTML CANVAS



Overview

HTML5, released in 2012, resulted in major modifications to the capabilities available to web developers. One of the notable additions was the canvas element. The canvas element allows developers to put a drawing canvas in the middle of their page. While the canvas element is written in HTML, we need JavaScript to draw on it. JavaScript is a client side programming language used in web design. Here is some sample code that draws a blue rectangle on a page with a line by line breakdown of the code:
<head>
    <script>
        function draw(){
            let canvas=document.getElementById('blueSquarePic');
            let context=canvas.getContext('2d');
            context.rect(100,75,50,25);
            context.strokeStyle='blue';
            context.stroke();
        }
    </script>
</head>    
<body onload='draw()'>
    <canvas id='blueSquarePic' width='300px' height='200px'></canvas>
</body>
Here is each line of this code in more detail:
  1. Declare the head of the html document. This is where information about the file is stored. Some programmers choose to store their JS functions here.
  2. The script tags are used to tell the browser that the code between them is JavaScript code. All code inside these tags must be JavaScript and all JavaScript code must occur within script tags. It is important when drawing that the script tags are placed after the canvas tag. This is because the canvas needs to be loaded by the browser before the JavaScript can write to it.
  3. A JS function called draw(). Placing code in a function holds its execution until the function is called.
  4. This line of code 'gets' the canvas element and gives the JavaScript code access to it.
  5. The getContext method, called from the canvas variable prepares the canvas for drawing. All drawing commands are called from the context. One way to think of it is that the canvas is the frame and the context is the actual area for painting.
  6. The rect method is designed to create a rectangle. The rect method takes four parameters. They are (in order): x coordinate of upper left corner, y coordinate of upper left corner, width, height. It is important to note that in computer graphics, the origin (0,0) is typically located in the upper left corner of the screen. The x values increase as we proceed right and the y values increase as we proceed down.
  7. Setting the strokeStyle sets the color of the outline of the shape. The color parameter can be set to any of the web safe colors. These colors include: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow. For more information on setting colors and stroke, see the drawing section below.
  8. This is the line of code that actually draws the rectangle on the canvas. The shape and color have been set prior to the drawing, so those are the settings that the stroke method uses. The stroke command draws only the outline of the shape. To fill the shape, we would call the fill() command. For more information about stroke vs fill, see the drawing section below.
  9. The end of the function.
  10. This line marks the end of the script section. Notice the / in the tag.
  11. This line marks the end of the head section. Notice the / in the tag.
  12. This line marks the beginning of the body section. The body is where all viewable content in a web page is placed. Also, note the event attribute of onload. The onload event fires when all of the content of the page has finished loading. We use this event to call the draw method to make sure that the canvas and any necessary images have been loaded prior to running the necessary drawing scripts.
  13. The canvas element allows web programmers to draw on the screen. It requires a closing and opening tag AND the use of three attributes:
    • id - a unique identifier on the page
    • width - an integer value in pixels
    • height - an integer value in pixels
    If desired, a border(frame) can be applied to the canvas using the style attribute with the following value: 'border:3px solid red'. In this property/value pair, the 3px is the width of the border, the solid is the style and red will be the color of the border.

Shapes

There are a variety of shapes that can be created in the context of a canvas. The following is a list of the shapes and the methods/parameters used to create them. Remember, createing the shape does not make it appear. You must follow the creation with a fill() or stroke() command.

Rectangles
A rectangle is created using the .rect() method. The .rect() method takes four parameters. The first two are the (x,y) coordinate of the upper left corner of the rectangle. The last two indicate the width and height, respectively, of the rectangle - stretching right and down from the upper left corner. To draw a square, make the width and height values equal.
context.rect(50,25, 10, 20);
Creates a rectangle whose upper left corner is at (50, 25) and from there extends left 10px and down 20px.
Circles
A circle is created using the .arc() method. The .arc() method takes six parameters. The first two are the (x,y) coordinate of the center of the circle. The third is the radius of the circle (in pixels). The fourth and fifth are the start and end measures of the arc. In other words, you can draw all of a circle, or part of a circle. The start and end measures are written in radians. A radian, similar to degrees, is a way to measure a central angle of a circle. Radians are based on the circumference of a unit circle. Thus, a full circle has a radian measusure of 2π. The value of 0 is the right most point of the circle. Finally, the last parameter, which is optional, is a true/false value that defines if the arc is drawn in the counterclockwise direction. Unless needed for the image, you should choose true to keep consistency with the unit circle we learn in mathematics.
context.arc(10, 15, 5, 0, Math.PI, true);
Creates a half circle with center at (10, 15) and radius=5 drawn in the counterclockwise direction from due east to due west (the top of the circle).
Lines
A line is created using the .moveTo() and .lineTo() methods. Both of these methods move the pencil to a given point on the canvas. The difference is that .moveTo() moves to a point without drawing, while lineTo() moves to a point and leaves a line between its starting and ending point. Both methods take two parameters, the (x,y) of the point that they are moving to (their end point).
context.moveTo(10,20); 
context.lineTo(40,40);
Creates a line that goes from the point (10,20) to (40,40).
Polygons
A polygon can be created by using a sequence of subsequent .lineTo() methods. These methods will enclose a space with straight line, thus creating a polygon. There is no need to draw a line back to the starting point as this will happen automatically.
context.moveTo(0,0); 
context.lineTo(0,30); 
context.lineTo(40,0);
context.lineTo(0,0);
Creates a triangle between the points (0,0), (0,30) and (40,0).

Stoke vs. Fill

Once a shape has been created using the above code, it needs to be drawn to the canvas. There are two choices when drawing on the canvas: .stroke() and .fill(). The .stroke() command draws only the outline of the shape while the .fill() command fills the interior of the shape. It is possible to call both methods which, with a color change, will produce an outline around the filled in shape.


Text

Text can also be drawn on the screen. To draw text, there are two options: strokeText() and fillText(). The strokeText() method draws the outline of the text on the canvas, while fillText() draws solid text on the canvas. Both of these methods take three parameters: the string to be output, the x coordinate of the upper left, and the y coordinate of the upper left.
context.fillText("This is text", 100, 20);    
context.strokeText("This is more text", 200, 20);
The first line draws the string "This is text" on the screen with the upper left corner at x=100, y=20. The text is solid.
The second line draws the outline of the text.
Additionally, the size and font of the text can be changed using the font property:
context.font="14pt Arial";
This will alter the text to be size 14 and in the Arial font.

Properties and Paths

There are a variety of properties that can be changed before objects are drawn to the canvas. These properties will allow the programmer to change the color, font and line width. They include:
Note that these are properties and use =, not methods that use ().

The problem is that if we draw a circle, set the fill color to green and fill it, and then draw a rectangle and set the color to blue, when wew call fill, it will re-fill everyting on the canvas. Thus, our circle will be colored blue. The same can be said for different text that we have drawn.

To eliminate this problem, we use an idea called a path. If we create, color and draw a shape or text in a path, it will be rendered on its own. Paths start with a beginPath() call and finish with a closePath() call. This is because a call to fill() or stroke() in a path, only renders the object in that path. Here is an example with our circle and rectangle:
//draw the circle
ctx.beginPath();
    ctx.arc(10,10,10,0, 2*Math.PI, true);
    ctx.fillColor="green";
    ctx.fill();
ctx.closePath();

//draw the rectangle
ctx.beginPath();
    ctx.rect(100,100,20,20);
    ctx.fillColor="blue";
    ctx.fill();
ctx.closePath();

Images

The canvas element allows programmers not only to draw shapes, but to add pre-created images. The canvas can display any image type that the browser can display, but to be safe, stick to using .jpg, .png or .gif.

The first thing that needs to be done when drawing an image on the canvas is to load the image. This is done using JavaScript. First, we create an Image object and store it in a variable. This just means that we are creating a place in memory to hold an image and we give that place a name. Next, we identify the source of the image using the .src property and a relative path to the image.
let img = new Image();
img.src = '../images/pic.png';    
function draw(){
    ...
    drawImage(img, 50, 20);
    ...
}
Note: This code should be placed in a script tag, but NOT inside the draw function. Placing the image code in free script includes the image in the items to be loaded on the page prior to activating the draw() funciton. If this code is placed inside the draw() function, the function code will execute prior to the image actually loading.
Once the image is loaded, we can draw it on the canvas. To do this, we use the drawImage method INSIDE the draw() function. The drawImage method takes three or five parameters (pieces of information). The standard version takes the image, and the x,y position of the upper left corner. So, to draw the image as created above:
context.drawImage(img, 20, 50);
The second option allows us to scale the image. In other words, the width and height can be altered to stretch or shrink the image as it is drawn on the canvas. To draw the image created above as a 100 wide by 150 high picture, the code is:
context.drawImage(img, 20, 50, 100, 150);