Game Development Reference
In-Depth Information
How to use it
The first thing we need to understand about the canvas element is that there are
two parts to it. One is the physical canvas element, and the other is the rendering
context through which we can draw to the canvas. As of this writing, there are two
rendering contexts that we can use in modern browsers, namely, CanvasRender-
ingContext2D and WebGLRenderingContext .
To obtain a reference to the rendering context of a canvas, we call a factory meth-
od on the canvas element itself.
var canvasA = document.createElement("canvas");
var ctx2d = canvas.getContext("2d");
ctx2d instanceof CanvasRenderingContext2D; //
True
var canvasB = document.createElement("canvas");
var ctx3d = canvas.getContext("webgl") ||
canvas.getContext("experimental-webgl");
ctx3d instanceof WebGLRenderingContext; // True
Note that the use of a fallback context is aimed at the prefixed experimental-
webgl context. As of this writing, most browsers that support WebGL will do so
through the experimental tag.
The rest of the section will relate exclusively to the CanvasRenderingContext2D
API. While it is technically possible to do everything that the 2D canvas context can,
using the 3D canvas context of WebGL, the only thing that these two APIs have in
common is their link to the HTML5 canvas element. WebGL is an entire program-
ming language in and of itself, and a single chapter dedicated to it would not be
enough to even scratch the surface.
Now, a very important aspect of the 2D rendering context is its coordinate space.
Similar to most coordinate system in computers, the origin is located at the top left
corner of the canvas. The horizontal axis increases to the right, while the vertical axis
increases downwards. The size of the grid held in memory to represent the canvas is
determined by the physical size of the canvas that generates the rendering context,
Search WWH ::




Custom Search