CanvasRenderingContext2D: setLineDash() 方法
Canvas 2D API 的 CanvasRenderingContext2D 介面中的 setLineDash() 方法用於設定繪製線條時使用的虛線模式。它使用一個數值陣列來指定交替的線條和間隙的長度,以描述虛線模式。
注意: 要恢復為實線,請將虛線列表設定為空陣列。
語法
js
setLineDash(segments)
引數
返回值
無(undefined)。
示例
基本示例
此示例使用 setLineDash() 方法在實線上方繪製一條虛線。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Dashed line
ctx.beginPath();
ctx.setLineDash([5, 15]);
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();
// Solid line
ctx.beginPath();
ctx.setLineDash([]);
ctx.moveTo(0, 100);
ctx.lineTo(300, 100);
ctx.stroke();
結果
一些常見模式
此示例演示了各種常見的虛線模式。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
下面建立的 drawDashedLine() 函式使繪製多條虛線變得簡單。它僅以一個模式陣列作為其唯一引數。
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let y = 15;
function drawDashedLine(pattern) {
ctx.beginPath();
ctx.setLineDash(pattern);
ctx.moveTo(0, y);
ctx.lineTo(300, y);
ctx.stroke();
y += 20;
}
drawDashedLine([]);
drawDashedLine([1, 1]);
drawDashedLine([10, 10]);
drawDashedLine([20, 5]);
drawDashedLine([15, 3, 3, 3]);
drawDashedLine([20, 3, 3, 3, 3, 3, 3, 3]);
drawDashedLine([12, 3, 3]); // Equals [12, 3, 3, 12, 3, 3]
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-setlinedash-dev |
瀏覽器相容性
載入中…