What does Canvas tag do?
What does the <canvas> tag ACTUALLY do then?
It provides a container to draw graphics. In simplest terms, it gives us a sheet in which we can draw whatever we want, of course using their limited keywords, but still it's pretty helpful. So, after the <canvas> tag gives us the blank sheet to draw we will need an object to actually draw something, just like in real life. For that we need the getContext() method which returns an object that provides methods and properties for drawing on the canvas.
The <canvas> tag has several methods to draw lines, boxes, rectangles, circles, text. You can also add images using the <canvas> tag. Let's take a look at the syntax:
<canvas id="canvas1" width="100" height="100" style="border: 1px solid black;"></canvas>
- We have also mentioned height and width for canvas because using that height and width, the browser will provide us a space of the same height and width to draw. So, make sure to mention all of those when you use <canvas> tag.
- Also, I've mentioned the border in style as well because the canvas will be there but you won't be able to visualize it until you draw something in it. So, before drawing anything, if you want to visualize taht canvas, you need to mention the border.
Let's take a look at the first simple example and try to draw a line.
<canvas id="Canvas1" width="200" height="200" style="border:1px solid black;"> The browser you are using, does not support the canvas tag.</canvas> <script> var canvas = document.getElementById("Canvas1"); var canvasObject = canvas.getContext("2d"); canvasObject.moveTo(0,0); canvasObject.lineTo(200,200); canvasObject.stroke(); </script>
We are using document method getElementById to get the canvas (like a drawing sheet or blank paper). Aftert that we need an object to draw on that canvas (think of canvas as a sheet or blank paper). For that we need to use getContext method. The getContext() method returns an object which provides methods and properties to draw anything on the canvas.
Then we need a starting point for our line. For that we are using moveTo method. The moveTo() method basically moves the path to the specified point in the canvas and that will be our starting point.
Now we need ending point for our line and for that we are using lineTo method. The lineTo() method adds ending point and creates an imaginary line, to that point from the moveTo point.
REMEMBER: moveTo or lineTo methods don't actually draw any lines. They just specify points in the canvas.
Now that we have everything, all we need is just a simple method to actually draw a line. For that we are using stroke() method which will use the path defined using moveTo and lineTo methods. The stroke method will use black as the default color.
We can easily chnage colors and make many more different shapes, which I am going to discuss in next few articles.