Canvas in HTML 5

As you well know HTML5 has some new elements including the Canvas element. A Canvas is an object that displays graphics in it.

But for a drawing process, we'll need to use JavaScript. You can draw anything you want: arcs, shapes, images, text and much more.

In our example we'll be drawing a shape.

Since HTML5 is platform independent, you can display these codes on any system.

You don't actually need First-Class Web Editors for building HTML5 sites; you just need a HTML5-supported Web Browser and a NotePad application.

Alright then let's start. First open a new NotePad application. And write the following code:

<!DOCTYPE html>
<
html>
<
head>
<
title>Canvas in HTML 5</title>
<
script type="text/javascript">
    function load_canvas() {
    }

</
script>
</
head>
<
body onload="load_canvas()">
<
h1>Canvas Example</h1>
<
canvas id="cnv1" width="500" height="500">
</
canvas>
</
body>
</
html>

What we have added here is a Javascript function that will run after page loaded.

And then we have added a canvas element with an id, width and height.

These parameters are needed while using a canvas.

So let's keep going. Create 2 variables inside the load_canvas function now:

var canvas = document.getElementById('cnv1');
var canvas1 = canvas.getContext('2d');


We'll be using these variables to access canvas elements from Javascript calls. As you can see above we have accessed the cnv1 object which we have set the "id" value in Canvas element.

Now add these codes after the codes above:

canvas1.fillStyle = "rgba(100, 200, 0, 1)";
canvas1.fillRect(30, 30, 75, 70);


Here we are creating a Rectangle object and filling it with a color as we have set it with rgba. These codes will display a rectangle with given width, height, x, y and rgba values in your canvas.

Full Code:

<!DOCTYPE html>

<html>
<
head>
<
title>Canvas in HTML 5</title>
<script type="text/javascript">
    function load_canvas() {
        var canvas = document.getElementById('cnv1');
        var canvas1 = canvas.getContext('2d');
        canvas1.fillStyle = "rgba(100, 200, 0, 1)";
        canvas1.fillRect(30, 30, 75, 70);
    }

</
script>
</
head>
<
body onload="load_canvas()">
<
h1>Canvas Example</h1>
<
canvas id="cnv1" width="500" height="500">
</
canvas>
</
body>
</
html>

Now save it as .html and view it in a HTML5 Supported Web Browser.

You'll get a similar view:

Canvas1.gif

But before that if you are using IE9 just like me,you'll be receiving this message before it can run:

Canvas2.gif

You'll need to Allow Blocked content.

We'll be talking more about Canvas in the following articles.
 

Up Next
    Ebook Download
    View all
    Learn
    View all
    Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.