lineCap:用於繪製線條兩端的樣式。屬性值有“butt”、“round”、“square”。
屬性值 | 作用 |
butt | 默認,線條的兩端爲平行的邊緣 |
round | 向線條的兩端添加半圓形線帽 |
square | 向線條的兩端添加正方形線帽 |
案例:
繪製三條直線,分別使用lineCap的三個屬性繪製末端,觀察區別。
代碼:
<body>
<canvas id="mycanvas" width="500" height="500"></canvas>
</body>
</html>
<script>
// 獲得canvas
var mycanvas = document.getElementById('mycanvas');
// 獲取上下文
var ctx = mycanvas.getContext('2d');
// 繪製第一條直線
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200,50);
ctx.strokeStyle = 'red';
ctx.lineWidth = 10;
// 使用butt
ctx.lineCap = 'butt';
ctx.stroke();
// 繪製第二條直線
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(200,100);
ctx.strokeStyle = 'green';
ctx.lineWidth = 10;
// 使用square
ctx.lineCap = 'square';
ctx.stroke();
// 繪製第三條直線
ctx.beginPath();
ctx.moveTo(50, 150);
ctx.lineTo(200,150);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 10;
// 使用round
ctx.lineCap = 'round';
ctx.stroke();
</script>
運行結果:
結論:
使用butt與square,直線兩端的樣式看似一樣,均爲方形。但是,square比butt兩端要長。因爲square相當與將兩個正方形拼接到線條的兩端,多處的部分就爲正方形的長度。使用round,線條兩端爲半圓形,長度不butt要長,相當於將兩個半圓拼接在線條的兩端。所以,"round" 和 "square" 會使線條略微變長。