HTML5 animations using Canvas | Cuelogic Blog

The HTML5 element is used to draw 2D graphics on the fly via JavaScript. The element is only a container for graphics. You need to use a JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters and adding images.

To use this first you need to define area to draw canvas (height and width of element) , there are several methods to generate graphics like fillRect, beginPath, etc. Following are some examples to draw canvas.

Step 1: Add canvas element into HTML

Step 2: Create canvas context object, context object has many properties to draw in canvas.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

Canvas co-ordinates starts from left top corner

Step 3: Draw gradient rectangle

To create gradient rectangle use following method, parameter is as follows, x = start top position of rectangle y = start bottom position of rectangle x1 = end top position of rectangle

y1 = end bottom position of rectangle

createLinearGradient(x,y,x1,y1)
var graRect = context.createLinearGradient(0,0,200,0);
graRect.addColorStop(0,"green");
graRect.addColorStop(1,"blue");
context.fillStyle=grd;
context.fillRect(10,10,150,80);

Step 4: Draw lines

To draw straight lines on a canvas, we will use the following two methods:

moveTo(x,y) defines the starting point of the line

lineTo(x,y) defines the ending point of the line

context.moveTo(0,0);
context.lineTo(200,100);
context.stroke();

Step 5: Draw circle

To draw a circle on a canvas, we will use the following method:

arc(x,y,r,start,stop)

context.beginPath();
context.arc(95,50,40,0,2*Math.PI);
context.stroke();

Step 6: Add text

To draw text on a canvas, the most important property and methods are:

font – defines the font properties for text fillText(text,x,y) – Draws “filled” text on the canvas

strokeText(text,x,y) – Draws text on the canvas (no fill)

context.font="30px Arial";
context.fillText("Hello World",10,50);