Coordinates in HTML Canvas

Canvas coordinates

The HTML canvas is a two-dimensional grid.

The top-left corner of the canvas is at (0,0).

In the previous chapter, we used the method: fillRect(0,0,150,75).

This means: start drawing a 150x75 pixel rectangle from the top-left corner (0,0).

Coordinate example

Hover the mouse over the following rectangle to view its x and y coordinates:

X
Y

Draw a line

To draw a straight line on the canvas, use the following methods:

  • moveTo(x,y) - Define the starting point of the line
  • lineTo(x,y) - Define the endpoint of the line

To actually draw a line, you must use one of the 'paint' methods, such as stroke().

Your browser does not support the HTML5 canvas tag.

Example

Define the starting point at position (0,0) and the endpoint at position (200,100). Then use the stroke() method to actually draw the line:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

Try It Yourself

Draw a circle

To draw a circle on the canvas, use the following methods:

  • beginPath() - Start a path
  • arc(x,y,r,startangle,endangle) - Create an arc/curve

To create a circle using arc(): set the starting angle to 0, and the ending angle to 2 * Math.PI. The x and y parameters define the x and y coordinates of the circle's center. The r parameter defines the radius of the circle.

Your browser does not support the HTML5 canvas tag.

Example

Define a circle using the arc() method. Then use the stroke() method to actually draw the circle:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

Try It Yourself

See Also:

Complete Canvas Reference Manual of CodeW3C.com