01 HTML 5 Canvas for Games

01 HTML 5 Canvas for Games

JavaScript Game Development

What is Canvas?

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing. Read More...

Basic Setup

You must retrieve the canvas element via JavaScript, after the DOM tree has been created. Usually, multiple canvas tags are used to boost performance. To start drawing, input the necessary content as follows:

<!--html-->
<canvas id="canvas"></canvas>
// JavaScript  
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

We draw using the "context" object. Take that as our "paint brush" for the canvas.

Coordinates in canvas

This section is fairly important to know and keep in mind! Drawing coordinates on computers is not the same as usual cartesian coordinates in math. (0, 0) is not in the center, it is located at the top left of the window. Anything above and below the window's width and height will exist and be sent to be drawn, but not be visible! Note how that is a performance problem.

X positioning is LEFT (negative) and RIGHT (positive) - also COLUMNS and WIDTH . Y positioning is UP (negative) and DOWN (positive) - also ROWS and HEIGHT.

javascript-game-development.png Play with the numbers below (line number 4 in codepen ) and try all kinds of numbers to get the idea! (x pos, y pos, width, height)

Group 2.png

Basic Canvas Features

Canvas can draw a rectangle, an arc, an ellipse, a line, and paths. A square would be a rectangle and a circle would be an arc. Other things we can do on canvas are scale, rotate, translate, transform, composite, style lines, strokes, fill, shadows, gradients, text, pixel manipulation, draw images, use CSS filters, use some CSS in general, and other things I can't recall off the top of my head.

There are 2 types of drawing: fill (which fills the shape with a color) and stroke (which only has an outline, or border). These can be mixed for outlined shapes. Stroke is great for checking and debugging collision bounds! It's not going to be used, but anything other than rectangles requires a "path" (shown below).

Frame 15.png

Fool around with the code below!

Next Chapter

Next time, we will look at a brief intro to game loops and start animating. Thank you, and I'll see you later.