Cuelogic Blog Icon
Cuelogic Career Icon
Home > Blog > All > HTML5 animations using Canvas

HTML5 animations using Canvas

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

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>

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

var graRect = context.createLinearGradient(0,0,200,0);

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


Step 5: Draw circle

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



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);