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).
Mouse over the rectangle below to see its x and y coordinates:
Draw a Rectangle
To draw a rectangle on the canvas, use the following method:
-
fillRect(x, y, width, height)
- defines the start-point and the width and height of the rectangle
Example
Define a start-point in position (0,0), and a width and height of 150px and 75px:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 150, 75);
</script>
Try it Yourself »
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
Define a start-point in position (0,0), and an end-point in position (200,100).
Then use the stroke()
method to actually draw the line:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
Try it Yourself »
Draw a Circle
To draw a circle on a canvas, use the following methods:
-
beginPath()
- begins a path -
arc(x, y, r, startangle, endangle)
- creates an arc/curve. To create a circle witharc()
: Set startangle to 0 and endangle to 2*Math.PI. The x- and y-coordinates define the center of the circle. r defines the radius of the circle
Example
Define a circle with the arc()
method. Then use the
stroke()
method to actually draw the
circle:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
Try it Yourself »