lineCap(路径样式属性)

context.lineCap=capStyle  // butt (default), round, square

设置线起点和终点的上限样式。

  • butt ,默认的 lineCap 样式,显示不超出线的起点和终点的平方上限。

  • 圆形,显示超出线的起点和终点的圆形帽。

  • 方形,显示延伸超出线的起点和终点的方形帽。

StackOverflow 文档

<!doctype html>
<html>
<head>
<style>
    body{ background-color:white; }
    #canvas{border:1px solid red; }
</style>
<script>
window.onload=(function(){

    // canvas related variables
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.lineWidth=15;

    // lineCap default: butt
    ctx.lineCap='butt';  
    drawLine(50,40,200,40);

    // lineCap: round
    ctx.lineCap='round';  
    drawLine(50,70,200,70);

    // lineCap: square
    ctx.lineCap='square';  
    drawLine(50,100,200,100);

    // utility function to draw a line
    function drawLine(startX,startY,endX,endY){
        ctx.beginPath();
        ctx.moveTo(startX,startY);
        ctx.lineTo(endX,endY);
        ctx.stroke();
    }

    // For demo only,
    // Rulers to show which lineCaps extend beyond endpoints
    ctx.lineWidth=1;
    ctx.strokeStyle='red';
    drawLine(50,20,50,120);
    drawLine(200,20,200,120);

}); // end window.onload
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=200></canvas>
</body>
</html>