gpt4 book ai didi

javascript - Canvas,如何设置线段虚线?

转载 作者:行者123 更新时间:2023-12-02 23:27:59 26 4
gpt4 key购买 nike

我只想用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>

最佳答案

最后我发现罪魁祸首是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>

关于javascript - Canvas,如何设置线段虚线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com