How to set linecap on HTML5 canvas

Description

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

Example


<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!--from www  .j av a 2 s  . com-->
      border: thin solid black
}

body>* {
      float: left;
}
</style>
</head>
<body>
      <canvas id="canvas" width="200" height="140"> 
      Your browser doesn't support the <code>canvas</code> element 
      </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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window