HTML 5 brings a lot of new elements and tags and hands them to developers / designers to develop websites. Previously I wrote about the <video> tag and how to create a video element and playing a video – Blog post can be found here. In this post, I’m going to explore the <canvas> tag. The Canvas element is an HTML object that allows for dynamic objects to be rendered on a webpage.

We can start of an HTML 5 document as follows:

<!DOCTYPE HTML>
<html>
<head>
<title>HTML 5 Canvas Tag Test</title>
</head>
<body>
... code goes in here
</body>
</html>

To create the canvas tag we just call <canvas>. There are 3 important parameters that we can apply to the <canvas> tag

id assigns an identifer to the <canvas> tag
width defines the width of the canvas tag
height defines the height of the canvas tag

With that in mind we apply those properties on our tag as follows. In this example we are going to designate the canvas as a 400×400 pixel canvas.

<canvas id="myCanvas" width="400" height="400"></canvas>

If we save everything and upload the file now, we would not see anything from our <canvas> tag. The only problem is, we did not assign anything to be rendered inside that canvas object and thus nothing is displayed.

In order to draw an object we can use javascript to draw a box inside of our object. In our case we want to draw a 200×200 pixel red box inside our canvas object.

<script>
var canvas = document.getElementById('myCanvas');
var canvasContext = canvas.getContext("2d");
canvasContext.fillStyle="#FF0000";
canvasContext.fillRect(0,0,200,200);
</script>

What we have done is accessed the canvas tag and applied the getContext object on the canvas. getContext() is a built in HTML 5 object that can create objects inside the canvas. We apply the getContext() in our canvasContext variable and with that we can assign the colour – fillStyle; red (#FF0000), and what object to draw – fillRect; (x, y, width, height – 0, 0, 200, 200). If we want to move the rectangle we can adjust the x and y values in the fillRect, which would change the x and y location of the red box we have just created.

That is it, we now can draw on our canvas using HTML 5 and Javascript.


This post is tagged , , , ,

One Response

  1. Cool info, I will keep my eye on it.

Leave a Reply

Categories