HTML Canvas Coordinates


Canvas Coordinates

The HTML canvas is two-dimensional.

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 150 x 75 pixels rectangle.


Coordinates Example

Coordinates Example (200px x 100px):

Mouse over this (200 x 100 pixels) rectangle to see its x and y coordinates:

X
Y

Draw a Line

To draw a straight line on a canvas, you use these methods:

  • moveTo(x,y) defines the starting point of the line
  • lineTo(x,y) defines the ending point of the line
Note 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, you use the following methods:

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

Example

Your browser does not support the HTML5 canvas tag.

Create a circle with the arc() method.

Then use the stroke() method to actually draw the line.

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 »




Color Picker

colorpicker