要为HTML5 Canvas线条添加上限,我们可以使用lineCap属性。 线条有3种末端线帽的样式:平直的边缘,圆形线帽或正方形线帽。 除非另有说明,HTML5 Canvas行默认为平直样式。 必须在调用stroke()之前设置lineCap属性。
html代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// butt line cap (top line)
context.beginPath();
context.moveTo(200, canvas.height / 2 - 50);
context.lineTo(canvas.width - 200, canvas.height / 2 - 50);
context.lineWidth = 20;
context.strokeStyle = '#0000ff';
context.lineCap = 'butt';
context.stroke();
// round line cap (middle line)
context.beginPath();
context.moveTo(200, canvas.height / 2);
context.lineTo(canvas.width - 200, canvas.height / 2);
context.lineWidth = 20;
context.strokeStyle = '#0000ff';
context.lineCap = 'round';
context.stroke();
// square line cap (bottom line)
context.beginPath();
context.moveTo(200, canvas.height / 2 + 50);
context.lineTo(canvas.width - 200, canvas.height / 2 + 50);
context.lineWidth = 20;
context.strokeStyle = '#0000ff';
context.lineCap = 'square';
context.stroke();
</script>
</body>
</html>