HTML5中lineCap端点样式遇到closePath()

时间:2023-03-08 20:52:08

定义和用法

lineCap 属性设置或返回线条末端线帽的样式。

注释:"round" 和 "square" 会使线条略微变长。

默认值: butt
JavaScript 语法: context.lineCap="butt|round|square";

属性值

描述
butt 默认。向线条的每个末端添加平直的边缘。
round 向线条的每个末端添加圆形线帽。
square 向线条的每个末端添加正方形线帽。

例子

        var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");//获取上下文2d环境
var lineCap = ["butt","round","square"];
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(10,150);
ctx.moveTo(150,10);
ctx.lineTo(150,150);
ctx.stroke();
ctx.closePath(); for (var i = 0; i < lineCap.length; i++) {
ctx.strokeStyle = "blue";
ctx.lineWidth = 20;
ctx.lineCap = lineCap[i];
ctx.beginPath();
ctx.moveTo(10,30*i+20);
ctx.lineTo(150,30*i+20);
ctx.stroke();
ctx.closePath();//此处两行不能颠倒位置,如果先闭合路径再绘制就不会有端点样式
};

效果图

HTML5中lineCap端点样式遇到closePath()