Canvas Element in HTML

Canvas Element in HTML5

Html 5 comes with a new advantage which is canvas element. Canvas element is a good replacement for flash. Now using canvas you can draw pictures, line and many other shapes in HTML. You can also use it for web based games and many other effects.

HTML canvas element uses some scripting languages to draw shapes and pictures. The <canvas> is the HTML property that only acts as a container for the graphics which were made using JavaScript.

Example:

To graphic startup development in the website using HTML canvas element first, we have to define a canvas element in our HTML file, and it’s better to give it a spate ID so that we easily get this area or element in our scripting language.

By default, the length and width of canvas element are zero, and it has no padding or border same like other HTML elements.

Now if we run the above code, it will show us nothing for two reasons.

  • 1: the border was not define
  • 2: we still have no script written for this.

Border of Canvas:

So to add border we use style attribute of HTML.

Error reports:

As we see the canvas is not a self-ending tag so what we do in the in-between space of starting and ending tags? Here we write the error message for the time when our browser does not support the graphics so that this message will appear on that time otherwise the message is hidden.

Get it in Script:

Now to get this canvas element in our script, we simply do what we do for other elements.

getContext():

The getContext() method returns an object that contains many built-in functions and for drawing shapes and pictures on the canvas element. The context may be 2d or 3d.

Draw Simple Line:

Today in this post to make it simple and basic we only draw a Line on canvas using JavaScript and context built-in function.

So to draw a line we need following functions:

  • beginpath();
  • moveto();
  • lineto();
  • stroke();

Begin Path:

This will define that the path we are using is a new path for some drawing and it is usually written at that start of the code.

Move To:

It is the starting position of the line. It takes two parameters which are x and y-axes.

Line To:

It is the ending point of the line. It also takes two parameters which are x and y-axes.

Stroke:

It is used to make line visible, and the default color of stroke is black.

The complete code for line:

Hope you like this tutorial, Stay Tuned! Stay Blessed!
Don’t forget to give us your feedback through comments.