Did you find this useful?
Socialize it today.


HTML5 Canvas: Lines

Thursday, October 25, 2012

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>

Your browser does not support the HTML5 canvas tag.

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>

Your browser does not support the HTML5 canvas tag.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

The Definitive Guide to HTML5 HTML5: The Missing Manual HTML CSS and JavaScript