CanvasRenderingContext2D: lineDashOffset 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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

浏览器兼容性

另见