Programming tutorials

Coordinate system

When you draw shapes on the HTML canvas, they are positioned using (x, y) coordinates, just like points on a graph.

However, unlike graph paper, the y values count down from the top of the canvas. So this code:

context.fillStyle = 'blue';
context.fillRect(100, 50, 200, 75);

creates something like this (assuming the canvas is 400 pixels wide and 200 pixels high):


The parameters are fillRect(x, y, width, height), which means that the top left of the rectangle is positioned 100 pixels from the left edge of the canvas, and 50 pixels down from the top. All measurements are in pixels.

This can be confusing at first, especially if you are drawing graphs or charts where you expect y to count up from the bottom of the canvas. Be prepared to get things upside down once in a while when you first start learning.