Canvas Coordinates

The canvas is a two-dimensional grid. The coordinate (0, 0) is at the upper-left corner of the canvas. Along the x-axis, values increase toward the right edge of the canvas. Along the y-axis, values increase toward the bottom edge of the canvas.

The coordinate diagram in Figure 4-2 was drawn with a <canvas> element. It comprises:

  • A set of off-white vertical lines

  • A set of off-white horizontal lines

  • Two black horizontal lines

  • Two small black diagonal lines that form an arrow

  • Two black vertical lines

  • Two small black diagonal lines that form another arrow

  • The letter “x”

  • The letter “y”

  • The text “(0, 0)” near the upper-left corner

  • The text “(500, 375)” near the lower-right corner

  • A dot in the upper-left corner, and another in the lower-right corner

Canvas coordinates diagram
Figure 4-2. Canvas coordinates diagram

In the following sections, we’ll explore how to create the effect shown in this figure. First, we need to define the <canvas> element itself. The <canvas> element defines the width and height of the rectangle, and the id so we can find it later:

<canvas id="c" width="500" height="375"></canvas>

Then we need a script to find the <canvas> element in the DOM and get its drawing context:

var c_canvas = document.getElementById("c");
var context = c_canvas.getContext("2d");

Now we can start drawing lines.

Get HTML5: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.