Canvas is perhaps one of those features of HTML5 which caused a great deal of stir among the web developers. In simple sense, canvas tag allows you to specify a region on your document where you can draw stuff. One thing to be noted is we have to use some sort of a scripting language (usually JavaScript) to interact with canvas. For today's article I'll assume you know the basics of JavaScript.
Creating a Canvas Element
Creating a canvas element is quite simple:
<canvas height = "200" width = "200" id = "canvas1" ></canvas>It is advised to always give a height and width to canvas element. A id is also necessary as there can be more than one canvas element in a single page.
The above code is actually as far as only HTML will take us, for functionalities of canvas we gotta use JavaScript as mentioned earlier. Please bear in mind any subsequent codes seen in this article must be written inside script tag or an external script file.
Understanding the Context
When we draw something on canvas, we actually retrieve the "context" of the canvas and put stuff on it. Broadly speaking, there are two types of context, 2d (mostly used) and 3d (still experimental). We will use the 2d context. Our first job is to identify our canvas element and create a handler to its 2d context. We do this by the following fragment:
var canvas = document.getElementById('canvas1'); var ctx = canvas.getContext('2d');We are first creating a handler to our canvas element (recall it had the id 'canvas1'), then we are retrieving its 2d context through the function getContext().
Basic Canvas Properties
Remember we grabbed the context just on the previous section? Now we are going to set some of its properties. First let's have a look at three basic properties:
-
fillStyle:
style to use when filling. We can specify CSS colors,gradients or patterns (defaults to black). -
strokeStyle:
style to use when filling. Constraints similar to that of fillStyle. -
lineWidth:
width of the lines drawn by our imaginary pen on canvas.
Drawing with colors and styles is a two step process. First one is to set the above properties. Other one is to perform the drawing operation i.e. calling the function which performs drawing.
Fill and Stroke
While dealing with canvas you'll find two versions of a function to create rectangles. these are fillRect and strokeRect ("Rect" standing for rectangle). What fill does is it creates the solid shape filled with the designated color/pattern, whereas stroke simply outlines the shape with that color. An example is presented shortly.
Before we append the following fragment to our code, let's have a look at the arguments that
the fillRect or strokeRect takes:
x-coord, y-coord, width, height
The coordinates specify the position of upper-left corner of the rectangle, and width and
height denotes the size of the rectangle. One reminder, the origin of the coordinate system
is situated at the top-left corner of the canvas. Now we can append the following segment:
ctx.fillStyle = 'tan'; ctx.fillRect(10, 10, 100, 100); ctx.lineWidth = 5; ctx.strokeStyle = 'red'; ctx.strokeRect(10 , 10, 100, 100);
First we chose the color tan and created a solid rectangle at (10, 10) having height and width of 100. Then we selected the lineWidth to be 5. Next we again selected a color, this time red; and stroked a rectangle at (10, 10) having similar dimensions as the previous rectangle. Notice although we have used colors as the property of fillStyle and such, we could have also used gradients or patterns, which is quite easily possible using CSS3.
Sample:Sample code:
<canvas id="CanvasFill" width="120" height="120"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var canvas = document.getElementById('CanvasFill'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'tan'; ctx.fillRect(10, 10, 100, 100); ctx.lineWidth = 5; ctx.strokeStyle = 'red'; ctx.strokeRect(10, 10, 100, 100); </script>
Drawing Lines
For drawing a line we are going to use four functions: beginPath, moveTo, lineTo and stroke. The function beginPath tells that we are going to create path. We move the imaginary pen to a location through lineTo function. Notice that by "moving the pen" I mean picking the tip of the pen up and then placing it down again at the designated coordinate. The function lineTo instructs to draw a line starting from the current point to th point passed as parameter of lineTo. But the line is actually not drawn unless we call the stroke function. Let's have a look at the following fragment of code:
ctx.lineWidth = 1; ctx.strokeStyle = 'black'; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(110, 110); ctx.stroke(); ctx.lineTo(200, 110); ctx.stroke();
We are setting the line width to be 1 and the color of the stroke to be black. Then we call the beginPath function. We move our imaginary pen to a point, in this case the point (10, 10). In the next line we instruct to create a line from (10, 10) to (110, 110). And finally to ensure the line is drawn, we call the stroke function. Notice that we created another line from the point where the previous line ended. If we wanted to draw a line from a different point we would have needed to call another moveTo function.
Sample:Sample code:
<canvas id="CanvasStroke" width="200" height="150"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var canvas = document.getElementById('CanvasStroke'); var ctx = canvas.getContext('2d'); ctx.lineWidth = 1; ctx.strokeStyle = 'black'; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(110, 110); ctx.stroke(); ctx.lineTo(200, 110); ctx.stroke(); </script>
Rendering Text
We can draw texts on canvas using fillText and strokeText functions. The arguments are:
text x-coord y-coord
Before calling these functions, we can also specify properties by assigning values to the
font property of our context. The order in which these properties are assigned is:
font-style font-weight font-size font-face
The following code illustrates the complete method:
ctx.strokeStyle = 'black'; ctx.fillStyle = 'black'; ctx.font = "normal normal 24px Tahoma"; ctx.fillText("Hello world", 10, 140);Sample:
Sample code:
<canvas id="CanvasText" width="200" height="100"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var canvas = document.getElementById('CanvasText'); var ctx = canvas.getContext('2d'); ctx.strokeStyle = 'black'; ctx.fillStyle = 'black'; ctx.font = "normal normal 24px Tahoma"; ctx.fillText("Hello world", 10, 40); </script>
The canvas of HTML5 has a vast domain. In this article I've tried to point out just some of the basic ideas. From here I'd suggest you search the net for a bit more info. As always w3schools has a precise collection of more or less all the features of canvas. Besides this mozilla developer site can also turn out to be really helpful. Although at first canvas might seem a bit intimidating, it is actually quite a great tool to have at hand. Bottom line, this is by far the best light-weight option to create graphic objects on the fly.