<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()
moveTo(x,y)
where x
is the horizontal coordinate and y
is the vertical coordinate.lineTo()
lineTo(x,y)
where x
is the horizontal coordinate and y
is the vertical coordinate.stroke()
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).
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.