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 line
- lineTo(x,y), which specifies the ending point of the line
Use one of the "ink" methods to draw a line, for example, the stroke().
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");
ctx.moveTo(0, 0);
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, that we have 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 path
- arc(x,y,r,startangle,endangle), which creates an arc/curve. If you want to create a circle with arc(): 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:
<!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();
ctx.arc(125, 95, 70, 0, 2 * Math.PI);
ctx.strokeStyle = '#1c87c9';
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 Your Knowledge
Quiz Time: Test Your Skills!
Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.