首页 > 解决方案 > Canvas, how to set line dash of line?

问题描述

I just want to draw a dashed line by canvas with lineDash is [1,1]. I found the function setLineDash, in theory, that can do it. But I cannot make it work and cannot figure out how the function work.

AFAIK, setLineDash function takes an argument that is an array. For example, setLineDash([1,1]) should set the dash length to 1 and the space length to 1 too. But, it does not. It just draws a solid line.

Please take a look at the snippet below.

const canvas = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')
canvas.width = 300
canvas.height = 300

ctx.lineWidth = 3
ctx.strokeStyle = 'red'

drawLine([1, 1], 25)
drawLine([2, 2], 50)
drawLine([3, 3], 75)
drawLine([4, 4], 100)
drawLine([5, 5], 125)
drawLine([6, 6], 150)
drawLine([7, 7], 175)
drawLine([8, 8], 200)
drawLine([9, 9], 225)

function drawLine(lineDash, y) {
  ctx.beginPath()
  ctx.setLineDash(lineDash)
  ctx.moveTo(200, y)
  ctx.lineTo(100, y)
  ctx.closePath()
  ctx.stroke()
}
<canvas id="myCanvas"></canvas>

标签: javascriptcanvas

解决方案


最后,我发现罪魁祸首是ctx.closePath()and的顺序ctx.stroke()。我在关闭路径后打电话ctx.stroke(),所以结果出错了。重新排序函数调用,它按预期工作。

const canvas = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')
canvas.width = 300
canvas.height = 300

ctx.lineWidth = 3
ctx.strokeStyle = 'red'

drawLine([1, 1], 25)
drawLine([2, 2], 50)
drawLine([3, 3], 75)
drawLine([4, 4], 100)
drawLine([5, 5], 125)
drawLine([6, 6], 150)
drawLine([7, 7], 175)
drawLine([8, 8], 200)
drawLine([9, 9], 225)

function drawLine(lineDash, y) {
  ctx.beginPath()
  ctx.setLineDash(lineDash)
  ctx.moveTo(200, y)
  ctx.lineTo(100, y)
  ctx.stroke()
  ctx.closePath()
}
<canvas id="myCanvas"></canvas>


推荐阅读