1) 线条笔帽篇:
1 function draw (id) { 2 var canvas = document.getElementById(id); 3 context = canvas.getContext("2d"); 4 buttDemo(); 5 roundDemo(); 6 squareDemo(); 7 } 8 function buttDemo (){ 9 context.beginPath(); 10 context.lineWidth = 10; 11 context.strokeStyle = "red"; 12 context.lineCap = "butt"; 13 context.moveTo(100, 100); 14 context.lineTo(200, 100); 15 context.stroke(); 16 } 17 function roundDemo (){ 18 context.beginPath(); 19 context.lineWidth = 10; 20 context.strokeStyle = "green"; 21 context.lineCap = "round"; 22 context.moveTo(100, 200); 23 context.lineTo(200, 200); 24 context.stroke(); 25 } 26 function squareDemo(){ 27 context.beginPath(); 28 context.lineWidth = 10; 29 context.strokeStyle = "blue"; 30 context.lineCap = "square"; 31 context.moveTo(100, 300); 32 context.lineTo(200, 300); 33 context.stroke(); 34 }
生成的为:

2) 线条连接篇:
1 function draw (id){ 2 var canvas = document.getElementById(id); 3 context = canvas.getContext("2d"); 4 miterDemo(); 5 roundDemo(); 6 bevelDemo(); 7 } 8 function miterDemo (){ 9 context.beginPath(); 10 context.lineWidth = 10; 11 context.strokeStyle = "red"; 12 context.lineJoin = "miter"; 13 context.moveTo(50,300); 14 context.lineTo(100,100); 15 context.lineTo(150,300); 16 context.stroke(); 17 } 18 function roundDemo (){ 19 context.beginPath(); 20 context.lineWidth = 10; 21 context.strokeStyle = "green"; 22 context.lineJoin = "round"; 23 context.moveTo(150,300); 24 context.lineTo(200,100); 25 context.lineTo(250,300); 26 context.stroke(); 27 } 28 function bevelDemo (){ 29 context.beginPath(); 30 context.lineWidth = 10; 31 context.strokeStyle = "blue"; 32 context.lineJoin = "bevel"; 33 context.moveTo(250,300); 34 context.lineTo(300,100); 35 context.lineTo(350,300); 36 context.stroke(); 37 }
生成的为:

值得说明的是:
代码
1 context.lineWidth = 10; 2 context.strokeStyle = "blue"; 3 context.lineCap = "square";
必须在
1 context.moveTo(100, 300); 2 context.lineTo(200, 300); 3 context.stroke();
的前面
即先设置笔触宽度,笔触颜色和笔帽方式。
原文:http://www.cnblogs.com/chenluomenggongzi/p/5170824.html