Set linecap on HTML5 canvas in JavaScript

Description

The following code shows how to set linecap on HTML5 canvas.

Example


<!DOCTYPE HTML>
<html>
<head>
</head><!--   w  w  w. j av  a  2  s.  c  o  m-->
<body>
<canvas id="canvas" width="200" height="140">
</canvas>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
ctx.strokeStyle = "red";
ctx.lineWidth = "2";
ctx.beginPath();
ctx.moveTo(20, 50);
ctx.lineTo(200, 220);
ctx.stroke();
ctx.strokeStyle = "black";
ctx.lineWidth = 40;
var xpos = 50;
var styles = [ "butt", "round", "square" ];
for ( var i = 0; i < styles.length; i++) {
ctx.beginPath();
ctx.lineCap = styles[i];
ctx.moveTo(xpos, 250);
ctx.lineTo(xpos, 20);
ctx.stroke();
xpos += 50;
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Set linecap on HTML5 canvas in JavaScript