HTML5 Canvas - Basics

In this post we will take a look at the HTML5 Canvas element and how to use it.

What is canvas?

HTML5 canvas element provides platform to draw stuff on it and also animate them.

How to create a Canvas?

Canvas is a html5 element, which is created as below:

<canvas id="mycanvas" width="578" height="200"></canvas>

How to get a handle to the canvas?

In order to draw shapes or write text into the canvas, we need to get a handle to the canvas object. This could be done in javascript as below:


      var canvas = document.getElementById('myCanvas');

      var context = canvas.getContext('2d');



Entire html code:




    <canvas id="myCanvas" width="578" height="250"></canvas>


      var canvas = document.getElementById('myCanvas');

      var context = canvas.getContext('2d');




The TODO line above is where we start writing javascript code to draw shapes etc and play around with the canvas. The code in the following sections are intended to be placed after the TODO.

How to draw a line?

Lines are drawn from the current position of the cursor till the destination x and y coordinates provided. Note that the coordinates are relative points from top left corner of the canvas.

To move the cursor around, we can use the moveTo function.

The width of the line could be set using the lineWidth attribute of canvas.
The color of the line could be set using the strokeStyle attribute of canvas. You can give either rgb values or hex values.

//move the cursor to position (100,200)
context.moveTo(100, 200);
//draw line from (100,200) to (400,100)
context.lineTo(400, 100);
//set line width
context.lineWidth = 10;
//set line color
context.strokeStyle = '##FE2E2E';

How to draw an arc?

To draw an arc, we need to specify the coordinates of the center of the circle and also the radius. The start and end angles decide how big or how complete the arc should be relative to the circle. Whether the arc should be drawn in clockwise/counter clockwise is decided by the last parameter (boolean).

var centerX = 250;
var centerY = 150;
var startAngle = 0.4 * Math.PI;
var endAngle = 1.8 * Math.PI;
var radius = 50;
var counterClockwise = false;
context.lineWidth = 5;

context.arc(centerX, centerY, radius, startAngle, endAngle, counterClockwise);

How to draw a circle?

Circle is a special case of arc, where the start angle is 0 and end Angle is 2* Math.PI.

How to draw a rectangle?

To draw a rectangle, use the rect() function, which takes the x and y coordinates of the top left corner of the rectangle, along with width and height.

var x = 100;
var y = 100;
var width = 300;
var height = 200;
context.rect(x, y, width, height);
context.fillStyle = 'red';


Popular posts from this blog

Pivotal Cloud Foundry (PCF) Integration with Elastic Cloud Storage (ECS)

Restful code example using Spring MVC

Spring Integration - Bulk processing Example