Posted on by & filed under Programming & Development, Web Development.

HTML5 will be the new standard for HTML, replacing the older 4.01 version. Although some browsers lack complete support, all major browsers have extensive support of essential HTML5 elements. HTML5 brings a whole new set of features; one of which is the Canvas element. Canvas can be used to draw objects on the fly in a web page. The Canvas element is only a container with immense possibilities of what you can achieve with it.

Declaring an HTML5 Document

You may already be familiar with it but for simplicity sake, you need to start your file with the following declarative tag to signal parsers that they’re dealing with an HTML5 file:

The Canvas Element

A canvas is a rectangular division on a web page that is empty by default. You put your content and draw images in it using JavaScript. The canvas is usually marked up like this:

It is recommended that you give your canvas an ID, so you can use that ID to style it using CSS. Read HTML 5 Canvas for a detailed discussion covering JavaScript in Canvas.

Drawing in Canvas

That was just the declaration, what you can do going forward is limited only by your imagination. Let’s cover the basics by filling your canvas with color.

Before your closing body tag, open a <script> tag for your JavaScript.

First, we need to find the <canvas> we drew, so use the div ID in the script below:

Now we must get the elements stored in canvas, using the getContext() function. We are going to pass “2d” to retrieve a 2D element (read Foundation HTML5 Canvas for details on 2d rendering):

This will save the data from Canvas_my canvas into the can variable. Now, we will fill it with color:

This will fill the Canvas element with the color black. The fillStyle property can be a CSS color, a gradient, or a pattern. There are many things you could do with your canvas container, for instance:

This replaces the content with “Sample Text.” Take a look in the HTML5 Canvas Cookbook for more about custom shapes and fill styles in Canvas.


In summary, the Canvas tag is a simple element with immense capabilities; you can insert pictures, change text, insert gradients and do anything related to pixels with it in HTML5.

About the author

Salman Ul Haq is a techpreneur, co-founder and CEO of TunaCode, Inc., a startup that delivers GPU-accelerated computing solutions to time-critical application domains. He holds a degree is Computer Systems Engineering. His current focus is on delivering the right solution for cloud security. He can be reached at

Tags: Canvas, Drawing in Canvas, fill, gradients, html5, Javascript, pixels,

Comments are closed.