CanvasRenderingContext2D:setLineDash() 方法
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
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"); // 虚线 ctx.beginPath(); ctx.setLineDash([5, 15]); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // 实线 ctx.beginPath(); ctx.setLineDash([]); ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke();
结果
一些常见的模式
此示例说明了各种常见的线划线模式。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
下面创建的 drawDashedLine()
函数使得多个虚线的绘制变得简单。它接收模式数组作为其唯一参数。
js
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]); // 等于 [12, 3, 3, 12, 3, 3]
结果
规范描述
Specification |
---|
HTML> # dom-context-2d-setlinedash-dev> |
浏览器兼容性
Loading…