HTML5 Canvas Element - Drawing a line


In the previous page we got started with the HTML5 canvas element. We draw a canvas of required length and height. There is a lot you can do inside a canvas. But in this tutorial we will just draw a simple line inside the canvas. Note that we will use javascript to do this, so, if you are not familiar with javascript we suggest that you take a look at the javascript tutorial .

If you are familiar with Javasript, you can go ahead and take a look at the following code. It draws a line in the canvas from coordinate (50, 50) to ( 200,100)

<!DOCTYPE html5>
<html>
<body>

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;">
</canvas>

<script>
var c1=document.getElementById("canvas1");
var context1=c1.getContext("2d");
context1.moveTo(50,50);
context1.lineTo(200,100);
context1.stroke();
</script>

</body>
</html>



Try this example Online


Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in the coordinates of the two end points of the line to see how it looks like.

Congratulations !!! You have been able to draw a line on the Canvas in HTML5. hrough and create your first HTML5 page.

Some Explanation



Notice the id canvas1 assigned to the element. We will use this id to access an instance of this canvas in javascript to draw a line.

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;"> 


Inside the javascript code we get a handle to the canvas element using.

var c1=document.getElementById("canvas1"); 


We then use the moveTo() method to position the of the starting point. Notice that the coordinate of the origine (0,0) is at the top left corner. The lineTo() method draws a straight line from the starting position to a new position. Finally, the stroke is used to make the line visible. By default the color of the strole in black.

Here is how the canvas looks like.