CanvasRenderingContext2D: lineDashOffset 屬性
Canvas 2D API 的 CanvasRenderingContext2D.lineDashOffset 屬性用於設定虛線偏移量(或“相位”)。
注意: 線條是透過呼叫 stroke() 方法繪製的。
值
一個浮點數,指定虛線偏移量的大小。預設值為 0.0。
示例
偏移虛線
此示例繪製兩條虛線。第一條沒有虛線偏移量。第二條虛線偏移量為 4。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.setLineDash([4, 16]);
// Dashed line with no offset
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();
// Dashed line with offset of 4
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.lineDashOffset = 4;
ctx.moveTo(0, 100);
ctx.lineTo(300, 100);
ctx.stroke();
結果
虛線偏移量為紅色的線條。
行進的螞蟻
“行進的螞蟻”(Marching ants)效果是一種動畫技術,常用於計算機圖形程式中的選擇工具。它透過為邊框新增動畫來幫助使用者區分選擇邊框和影像背景。
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let offset = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setLineDash([4, 2]);
ctx.lineDashOffset = offset;
ctx.strokeRect(10, 10, 100, 100);
}
function march() {
offset++;
if (offset > 5) {
offset = 0;
}
draw();
setTimeout(march, 20);
}
march();
規範
| 規範 |
|---|
| HTML # dom-context-2d-linedashoffset-dev |
瀏覽器相容性
載入中…