THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML Canvas Coordinates


Canvas Coordinates

The HTML canvas is a two-dimensional grid.

The upper-left corner of the canvas has the coordinates (0,0)

In the previous chapter, you saw this method used: fillRect(0,0,150,75).

This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle.


Coordinates Example

Mouse over the rectangle below to see its x and y coordinates:

X
Y

Draw a Line

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

  • moveTo(x,y) - defines the starting point of the line
  • lineTo(x,y) - defines the ending point of the line

To actually draw the line, you must use one of the "ink" methods, like stroke().

Example

Your browser does not support the HTML5 canvas tag.

Define a starting point in position (0,0), and an ending point in position (200,100). Then use the stroke() method to actually draw the line:

var canvas = document.getElementById("myCanvas");
var 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 a canvas, use the following methods:

  • beginPath();
  • arc(x,y,r,start,stop)

Example

Your browser does not support the HTML5 canvas tag.

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

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