Line Ending In Canvas: HTML5

Today lets learn about line ending properties present in HTML5.

The property we’re using is lineCap. It has 3 values: butt, round, square.

index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5

Javascript file: First Line
myScript.js

context.lineWidth=15;
  
  context.beginPath();
  context.lineCap="butt";
  context.moveTo(10, 50);
  context.lineTo(190, 50);
  context.strokeStyle="red";
  context.stroke();

Here we set the lineWidth to 15px. Begin the path and give it a lineCap(line ending) value of butt, and make it red colored.

Javascript file: Second and third Line
myScript.js

context.beginPath();
  context.lineCap="round";
  context.moveTo(10, 75);
  context.lineTo(190, 75);
  context.strokeStyle="blue";
  context.stroke();
  
  context.beginPath();
  context.lineCap="square";
  context.moveTo(10, 100);
  context.lineTo(190, 100);
  context.strokeStyle="green";
  context.stroke();    

Similarly, we draw 2 more lines: with round and square lineCap and blue and green colors respectively.

Javascript file: line endings
myScript.js

  context.lineWidth=1;
  context.beginPath();
  context.moveTo(10, 0);
  context.lineTo(10, 200);
  context.strokeStyle="pink";
  context.stroke();

  context.beginPath();
  context.moveTo(190, 0);
  context.lineTo(190, 200);
  context.strokeStyle="pink";
  context.stroke();

Here we change the lineWidth to 1px. Then mark a border and separate the line ending shapes with the actual line itself.

Full Javascript Code file
myScript.js

window.onload = canvas;

function canvas()
{
 var myCanvas = document.getElementById("myCanvas");
 
 if( myCanvas && myCanvas.getContext("2d") ) 
 {
  var context= myCanvas.getContext("2d");
  
  
  context.lineWidth = 15;
  
  context.beginPath();
  context.lineCap="butt";
  context.moveTo(10, 50);
  context.lineTo(190, 50);
  context.strokeStyle= "red";
  context.stroke();

  context.beginPath();
  context.lineCap="round";
  context.moveTo(10, 75);
  context.lineTo(190, 75);
  context.strokeStyle = "blue";
  context.stroke();
  
  context.beginPath();
  context.lineCap="square";
  context.moveTo(10, 100);
  context.lineTo(190, 100);
  context.strokeStyle = "green";
  context.stroke();    
  
  context.lineWidth= 1;
  context.beginPath();
  context.moveTo(10, 0);
  context.lineTo(10, 200);
  context.strokeStyle= "pink";
  context.stroke();

  context.beginPath();
  context.moveTo(190, 0);
  context.lineTo(190, 200);
  context.strokeStyle= "pink";
  context.stroke();

  
 }
}

Line Ending In Canvas: HTML5



YouTube Link: https://www.youtube.com/watch?v=FcoonQCq2Jw [Watch the Video In Full Screen.]



By default line ending(lineCap) has a value butt.

In our next video lessons, lets learn about the curves.