javascriptcanvas

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>


Solution

  • Finally, I found the culprit is the order of ctx.closePath() and ctx.stroke(). I called ctx.stroke() after closing the path so it makes the result go wrong. Re-order the function call and it works as expected.

    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>