画布,如何设置线点划线?

时间:2019-06-18 09:48:22

标签: javascript canvas

我只想用lineDash用[1,1]画一条虚线。从理论上讲,我发现函数setLineDash可以做到。但是我无法使其工作,也无法弄清楚该功能如何工作。

AFAIK,setLineDash函数采用的参数是数组。例如,setLineDash([1,1])也应将破折号长度设置为1,空格长度也应设置为1。但是,事实并非如此。它只是画一条实线。

请查看下面的代码段。

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>

2 个答案:

答案 0 :(得分:1)

最后,我发现罪魁祸首是ctx.closePath()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>

答案 1 :(得分:0)

尝试一下

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([1, 1]);
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(200, 100);
ctx.stroke();
<canvas id='canvas' width='350px' height='300px'></canvas>

相关问题