HTML5 > Canvas

HTML5 > Canvas


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.

Canvas Coordinates

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.

HTML5 Canvas Coordinates

Applying CSS to Canvas

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.

Drawing on Canvas

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

Read posts under HTML5 > Canvas

14 posts found
  1. Canvas Transformations
  2. Canvas Texts
  3. Canvas Gradients
  4. Canvas Images
  5. Image masking on Canvas
  6. Canvas in Scroll bar
  7. Canvas line
  8. Canvas Rectangle
  9. Canvas Circle
  10. Canvas Arc
  11. Canvas Paths
  12. Clear Canvas
  13. Canvas Mouse Events
  14. Canvas Hover



Write for us






Hosting Recommendations