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

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 https://www.youtube.com/watch?v=FcoonQCq2Jw]

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.