In this section we are going to learn the Canvas in HTML5.
Canvas element is a rectangular area that can be used to draw lines, shapes, images, animations. Canvas doesn’t have its own drawing abilities; it is done through JavaScript programmatically. The default area of the canvas is 300x150 px (Width x Height) however the width
and height
attribute can be specified to customize them.
To draw any shape or size on the canvas, we must understand the coordinates of canvas. This will help us to understand how drawing is done on canvas.
Canvas drawing starts at x=0, y=0 position as shown in the picture and this is top-left corner of the canvas element. This we are referring as "Origin". From here, the horizontal increase goes to X-Axis and vertical down goes to Y-Axis.
CSS styles can be applied to the canvas element to apply border with color, width etc. however the drawing on the Canvas doesn't inherits these css properties. To apply styles to the canvas drawing, we need to call appropriate context method that we will see in next posts.
To start drawing on the canvas, first we need to get the context of the HTML5 Canvas element using getContext()
method on the canvas element.
After getting the context, we need to instruct the context that we are going to create a new path or if any other path is open, reset that path using context beginPath()
method.
After that we need to call moveTo()
method to move the starting position of the path, this method accepts x and y axis to move so moveTo(50, 60) would move the starting position of the path to 50px from X and 60px from Y axis.
Then we can call drawTo, lineTo and other method to virtually draw lines or drawing. Once we are done with the drawing, we can call closePath()
method that acutally goes back to the starting position. Note that closePath() doesn't accepts any parameter, it simply goes back to the starting position where first moveTo() method was called.
function DrawLines()
{
var context = document.getElementById("Canvas1").getContext("2d");
context.beginPath();
context.moveTo(50, 60);
context.closePath();
}