How to draw lines using html5 canvas?

We read about html5 canvas in last post, we can do lot with canvas. As today, i am going to learn how to draw lines using html5 canvas. HTML5 canvas having a lot of things to learn so we learn various small-2 things regularly.

To draw lines, canvas used 4 methods beginPath(), moveTo(), lineTo(), and stroke() methods. Lets know more about them in detail –

beginPath() –  this methods reset the current path or declare a new path.

moveTo(x,y) –  it creates a new sub-path with the given point.

lineTo() – it adds the given point to current subpath.

stroke() – it draws the line actually, gives the visibility to line.

Lets draw a line –

 <canvas id="testCanvas" width="400" height="200" style="border:1px solid #d3d3d3;"></canvas>
    <script>
      var canvas = document.getElementById('testCanvas');
      var context = canvas.getContext('2d');

      context.beginPath();
      context.moveTo(100, 150);
      context.lineTo(200, 50);
      context.stroke();
    </script>

As we can see in the above example, we created an canvas and given a border, height and width to it because as we know canvas does not contain any border or content in it .

Now, lets start  drawing line. First we need to find canvas by its id and call the getContext() method to draw –

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

Now, call beginPath() to declare a new path, then moveTo() to create a subpath , then lineTo() to add a new point to connect it to previous point and at last stroke() method to draw line.

context.beginPath();
      context.moveTo(100, 150);
      context.lineTo(200, 50);
      context.stroke();

You can learn by changing x, y coordinates to see how these method works. The results will be look like this.

how to draw lines html5 canvas

Leave a Reply