Falcon80 Logo
Drawing straight lines on canvas

Defining a line

Once you understand the concept of paths on canvas, drawing lines is a simple task. A line has two end points (x1,y1) and (x2,y2).
Line
Required Methods

You will need the following methods to draw a line.
  • strokeStyle:
The strokeStyle() method defines the colour of any figure drawn on the canvas. Here, we will use it to define the colour of the line we are about to draw. If you do not specify strokeStyle, the default colour will be black
  • moveTo(x1,y1):
We will use the moveTo() method to define the point where our line begins  - (x1,y1). This method will only position the pen on (x1,y1) and will not actually draw anything on the canvas.
  • lineTo(x2,y2):
The lineTo() method will draw a line from the last point in the path to the point (x2,y2). In this case, our last point in the path would be at (x1,y1). So we will get a line from (x1,y1) to (x2,y1). Note that like the moveTo() method, the lineTo() method will not actually draw anything on the canvas. Once you define all the lines using the lineTo() method, the actual lines will be drawn only after the stroke() method.
  • stroke():
The stroke() method draws all the paths that are currently defined and not yet drawn on the canvas. In our example, it will draw the actual line from point (x1,y1) to point (x2,y2). 

<html>
<head>
<script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");

//define the colour of the line
ctx.strokeStyle = "red";

//define the start point (x1,y1)

ctx.moveTo(50,50);

//define the end point (x2,y2)

ctx.lineTo(600,50);

//draw the line from (x1,y1) to (x2,y2)

ctx.stroke();
}
}
</script>
</head>
<body>
<canvas id="canvas" width="900" height="100">
</canvas>
</body>
</html>

Try Code