HTML5 Canvas Line Cap


In the previous page we learned how to draw a line with a given color. The end of the line can take one of the three styles and this is the subject to learning in this tutorial.

To change the way the ends of the line look like, we use the lineCap property. Lines can have one of three cap styles: butt, round, or square. By default, the lines have butt cap style. The lineCap property is set before calling stroke().

The following example will draw the lines three end styles.


<!DOCTYPE html5>
<html>
<body>

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;">
</canvas>

<script>
var c1=document.getElementById("canvas1");
var context1=c1.getContext("2d");
context1.beginPath();
context1.moveTo(50,50);
context1.lineTo(200,50);
context1.lineWidth = 10;
context1.lineCap = 'butt';
context1.stroke();

context1.beginPath();
context1.moveTo(50,100);
context1.lineTo(200,100);
context1.lineWidth = 10;
context1.lineCap = 'round';
context1.stroke();



context1.beginPath();
context1.moveTo(50,150);
context1.lineTo(200,150);
context1.lineWidth = 10;
context1.lineCap = 'square';
context1.stroke();

</script>

</body>
</html>



Try this example Online


Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in the lengths and colors to see the relative color or ends look and shape.

Congratulations !!! You have been able to change the way the ends of the line line look like using lineCap property.

So how to we draw circle on the canvas in HTML5. Read in the next post.