articles

Home / DeveloperSection / Articles / Canvas Element in HTML5

Canvas Element in HTML5

Anonymous User7979 25-Jul-2011

Canvas element will be used to draw some graphics content on browser by using java script. It is a resolution dependent bitmap canvas, which can be used for rendering graphs, game graphics or other visual images on the fly. The canvas element has several methods for drawing paths, boxes, circles, character and adding images. The canvas element uses java script to draw graphics on webpage.

The markup for canvas element looks like this:

<canvas id=”canvas_id_name” width=”200” height=”200”></canvas>

Following code snippet represents use of canvas element in html5

This set of html element creates a canvas element of width 100 and height 100.

<canvas id="canvas" width="100" height="100"style="border: solid 1px black;"></canvas>


On load event of body element call draw() java script function which will fill color in canvas element.

function draw()
{
            var canvas = document.getElementById("canvas");      //Retriving current canvas element,
            if (canvas.getContext)    //Check if get context method will return true.
            {
                var ctx = canvas.getContext("2d");    //The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions.This function takes one parameter the type of context 2d
 
                ctx.fillStyle = "rgb(200,0,0)";   //Fill canavas using specified color.
                ctx.fillRect(0, 0, 150, 75);      //Fill rectangle.
 
                ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
                ctx.fillRect(40, 30, 125, 75);
 
                ctx.fillStyle = "rgb(0,0,150)";
                ctx.strokeRect(20, 20, 50, 100);
            }
}
The output of this method is as follows:

Canvas Element in HTML5

Now for displaying gradient canvas call displayGradientColor() method on load event of body element.

function displayGradientColor() {
            var canvas = document.getElementById("canvas");      //Retriving current canvas element,
            if (canvas.getContext)    //Check if get context method will return true.
            {
                var context = canvas.getContext("2d");
                var myGradient = context.createLinearGradient(0, 0, 100, 50);   //Creating linear gradient object.
                myGradient.addColorStop(0, "#ccff00");
                myGradient.addColorStop(1, "#00bbcc");
                context.fillStyle = myGradient;
                context.fillRect(25, 25, 125, 125);
            }
}

 

The output of following code snippet is as follows

Canvas Element in HTML5

The canvas control is supported by Internet explorer, Mozilla Firefox, Opera and Google Chrome.



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By