Draw a line using the HTML <canvas> Tag
<canvas id="myCanvas" width="350" height="350">
<p>Fallback content for browsers that don't support the canvas tag.</p>
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Black line
ctx.beginPath();
ctx.moveTo(5,5);
ctx.lineTo(120,120);
ctx.stroke();
// Orange line
ctx.beginPath();
ctx.strokeStyle = 'Orange';
ctx.moveTo(5,280);
ctx.lineTo(120,180);
ctx.stroke();
</script>
The above example demonstrates how to draw a straight line using the HTML <canvas>
element.
We draw two lines; The first line uses the default color (black), and the second line is drawn in orange.
The above lines are defined with the moveTo()
, lineTo()
, and stroke()
methods. Here's an explanation:
moveTo()
- Creates a new subpath with the given point. Accepts two coordinates as
moveTo(x,y)
wherex
is the horizontal coordinate andy
is the vertical coordinate. lineTo()
- Adds the given point to the current subpath, connected to the previous one by a straight line. Accepts two coordinates as
lineTo(x,y)
wherex
is the horizontal coordinate andy
is the vertical coordinate. stroke()
- Strokes the subpaths of the current path or the given path with the current stroke style.
The default color of the line is black — if nothing further is specified when the context is created, the line will have a stroke value of #000000
(black).
Style a Line
You can change the line's color from the default black. In the above example, we use ctx.strokeStyle = 'Orange';
to specify a color for the line.
Note that we must use ctx.beginPath();
to reset the path, otherwise both lines would be painted orange. This is because, within a path, the last style that is specified is applied to the whole path.