HTML5 Game - Different lineCap settings in action

Introduction

The following code shows how to set the lineWidth and lineCap Properties

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){// www.  j a  va 2 s .  co  m
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
     context.lineWidth = 10; 

     context.beginPath(); 
     context.moveTo(20, 100); 
     context.lineTo(180, 100); 
     context.lineCap = "butt"; 
     context.stroke(); 

     context.beginPath(); 
     context.moveTo(20, 120); 
     context.lineTo(180, 120); 
     context.lineCap = "round"; 
     context.stroke(); 

     context.beginPath(); 
     context.moveTo(20, 140); 
     context.lineTo(180, 140); 
     context.lineCap = "square"; 
     context.stroke(); 
        
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

In the code above, the width of the lines to be drawn is set to 10 pixels using the lineWidth property.

Then the code draws three lines by setting lineCap to butt, round, and square, respectively.

The use of the beginPath() method starts a new drawing path.

A path is a series of drawing operations.

If you don't call beginPath(), all lines are redrawn with the last lineCap setting.

The last two lines add extra pixels to the overall length, whereas the first line is precisely drawn as per the start and end coordinates.

Related Topic