Canvas introduction – Starting with Canvas

HTML5 includes the canvas element, you can create graphics, animation, shapes etc on the canvas using JavaScript at run time. There are JavaScript methods and properties for drawing text, lines, curved paths, and shapes, as well as for rendering images and video. So canvas element is useful when you need to design a attractive website or when you need to image processing, you can also create the games.

Create the Canvas
You can create a canvas element with <canvas> opening and ending tags just like other html elements:
<canvas id="mycanvas"></canvas>

you can also specify the height and width for the canvas element:

<canvas id="mycanvas" height="400px width="500px"></canvas>

Start with canvas

firstly get the object of the canvas and create its 2d drawing context using javaScript as:

var objCanvas = document.getElementById("myCanvas");
var objContext = objCanvas.getContext("2d");

now you can work with the canvas, draw lines and shapes etc.

Canvas Coordinates

Canvas element has the two-dimensional coordinate system. The starting point will be (0,0) at the upper left corner( see the figure 1).

Canvas cordinates

We draw any shape according to these coordinates to specify the location and size.
Start with Rectangle
To understand the coordinate system of the canvas, we will see how to draw and fill a rectangle shape on the canvas.
Suppose we want to draw a rectangle with height of 200 and width of 300 on the location (50,50).
For it we use the following methods in JavaScript:
To Draw a filled rectangle: fillRect(x,y,width,height)
To Draw a rectangular outline: strokeRect(x,y,width,height)
And full program is:

            outline: 1px solid #000;
    <script type="text/javascript">
        function DrawRectangle() {
            var objCanvas, objContext;
            objCanvas = document.getElementById('myCanvas');
            objContext = objCanvas.getContext('2d');
            objContext.fillStyle = "Red";
            objContext.fillRect(50, 50, 300, 100);
<body onload="DrawRectangle()">
    <canvas id="myCanvas" width="500" height="300" />

and Output will be:

This is basic explanation of the canvas element. For better understand go through next articles.