CanvasRenderingContext2D.lineDashOffset

CanvasRenderingContext2D.lineDashOffset 是 Canvas 2D API 设置虚线偏移量的属性,例如可以实现 “蚂蚁线“ 的效果。

语法

ctx.lineDashOffset = value;
value
偏移量是float精度的数字。 初始值为 0.0。

示例

使用 lineDashOffset 属性

这是一段简单的代码片段,使用 lineDashOffset 属性绘制虚线。

HTML

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.setLineDash([4, 16]);
ctx.lineDashOffset = 2;

ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();

修改下面的代码并在线查看 canvas 变化:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code" style="height: 120px">
ctx.setLineDash([4, 16]);
ctx.lineDashOffset = 2;

ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", function() {
  textarea.focus();
})

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

“蚂蚁线”

”蚂蚁线“效果是一种动画技巧,经常出现在计算机绘图程序的套索工具中。 它能帮助用户根据图片背景动态变化的边界来区分选择的边界。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var 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 > 16) {
    offset = 0;
  }
  draw();
  setTimeout(march, 20);
}

march();

规范描述

Specification Status Comment
HTML Living Standard
CanvasRenderingContext2D.lineDashOffset
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
lineDashOffsetChrome Full support YesEdge Full support 12Firefox Full support 27
Full support 27
Full support 7
Alternate Name
Alternate Name Uses the non-standard name: mozDashOffset
IE Full support 11Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 27
Full support 27
Full support 7
Alternate Name
Alternate Name Uses the non-standard name: mozDashOffset
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
Uses a non-standard name.
Uses a non-standard name.

参见