The Canvas element is new to HTML5. You can use the canvas to draw lines, shapes, text, and more. To draw a line onto the HTML5 Canvas, we will use various methods. The most common methods used in drawing lines are
beginPath(), moveTo(), lineTo(), and stroke(). The beginPath() mehtod is to declare that we want to draw a line. Next is the moveTo(), which is used to position the context point. Then we use the lineTo() method to
draw a straight line from the starting point to the new target point. Finally, we use the stroke() method to apply a stroke to the line and make it visible. The default stroke color is black, but we can style the line's color (strokeStyle) as well
as other properties such as width (lineWidth) or cap (lineCap). You should note that Internet Explorer 8 and earlier versions, do not support the <canvas> element, nor the Context properties and/or methods.
Syntax
context.beginPath();
context.moveTo(x, y);
context.lineTo(x, y);
context.stroke();
Example
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #AAAAAA;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(100, 50);
context.lineTo(300, 150);
context.stroke();
</script>
Line Styling: Width, Color, and Cap
The lineWidth property sets or returns the current line width, and the lineCap property sets or returns the style of the end caps for a line. The strokeStyle property sets or returns the color, gradient, or patterns.
context.lineWidth=number;
context.lineCap="butt|round|square";
context.strokeStyle=color|gradient|pattern;
Here is an example of how to apply a different width, color, and cap to a line. You should note that the lineCap values of "round" and "square" increase the length of the line. The default value is "butt".
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(100, 50);
context.lineTo(300, 150);
context.lineWidth = 5;
context.lineCap = "round";
context.strokeStyle = '#FFAA00';
context.stroke();
</script>
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources