Canvas Coordinates
HTML canvas is a powerful element in HTML5 that allows you to create and manipulate graphics on a web page using JavaScript. The canvas element provides a two-dimensional drawing surface, which can be thought of as a grid or coordinate system, the upper-left corner of which has the coordinates (0,0). The X-axis increases horizontally to the right, and the Y-axis increases vertically downward. Each point in the canvas is represented by a pair of coordinates (x, y) that define its position within the grid.
Drawing a Line
The methods below are used to draw a straight line on a canvas:
moveTo(x,y), which specifies the starting point of the linelineTo(x,y), which specifies the ending point of the line
Use one of the "ink" methods to draw a line, for example, stroke().
Example of the HTML <canvas> element to draw a line:
Example of the HTML <canvas> element to draw a line
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<canvas width="300" height="150" style="border:1px solid #cccccc;" id="canvasExample">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("canvasExample");
var ctx = c.getContext("2d");
// Starting point (0,0) is the top-left corner
ctx.moveTo(0, 0);
// Ending point (300,150) matches the canvas width and height
ctx.lineTo(300, 150);
ctx.strokeStyle = '#359900';
ctx.stroke();
</script>
</body>
</html>In the example above, we have defined the starting and ending points of the line, and used the stroke() method to draw it.
Drawing a Circle
The methods below are used to draw a circle on a canvas:
beginPath(), which begins a patharc(x,y,r,startangle,endangle), which creates an arc/curve. If you want to create a circle witharc(): set start angle to 0 and end angle to 2 * Math.PI. The x and y specify the x- and y-coordinates of the circle’s center. The r parameter specifies the radius of the circle.
Example of the HTML <canvas> element to draw a circle:
Example of the HTML <canvas> element to draw a circle:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<canvas id="exampleCanvas" width="250" height="200" style="border:1px solid #dddddd;">
The canvas tag is not supported by your browser.
</canvas>
<script>
var canvas = document.getElementById("exampleCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
// Center at (125, 95), radius 70. 125 is half of the 250 width.
ctx.arc(125, 95, 70, 0, 2 * Math.PI);
ctx.strokeStyle = '#1c87c9';
ctx.closePath();
ctx.stroke();
</script>
</body>
</html>In the example above, we have defined a circle with the arc() method and used the stroke() method to draw the circle.
Practice
What are the characteristics of the HTML5 <canvas> element coordinates?