setLineDash() method of the Canvas 2D API's CanvasRenderingContext2D interface sets the line dash pattern used when stroking lines. It uses an array of values that specify alternating lengths of lines and gaps which describe the pattern.

注意: To return to using solid lines, set the line dash list to an empty array.

句法

ctx.setLineDash(segments);
					

参数

segments
数组 of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25] . If the array is empty, the line dash list is cleared and line strokes return to being solid.

返回值

undefined .

范例

基本范例

此范例使用 setLineDash() method to draw a dashed line above a solid line.

HTML

<canvas id="canvas"></canvas>
					

JavaScript

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();
					

结果

Some common patterns

This example illustrates a variety of common line dash patterns.

HTML

<canvas id="canvas"></canvas>
					

JavaScript

drawDashedLine() function created below makes the drawing of multiple dashed lines simple. It receives a pattern array as its only parameter.

function drawDashedLine(pattern) {
  ctx.beginPath();
  ctx.setLineDash(pattern);
  ctx.moveTo(0, y);
  ctx.lineTo(300, y);
  ctx.stroke();
  y += 20;
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let y = 15;
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 实时标准
The definition of 'CanvasRenderingContext2D.setLineDash' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
setLineDash Chrome 23 Edge 12 Firefox 27 IE 11 Opera 15 Safari 6.1 WebView Android ≤37 Chrome Android 25 Firefox Android 27 Opera Android 14 Safari iOS 7 Samsung Internet Android 1.5

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: