javascript - 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>
解决方案
最后,我发现罪魁祸首是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>
推荐阅读
- vue.js - 带点的按钮分页
- reactjs - Redux + 修改和发送状态 - 在状态中检测到不可序列化的值
- windows - 使用 EV 签名证书签署 Windows 驱动程序需要哪些步骤?
- c# - 为什么流利的 Hibernate .Sum 在空表中使用时会抛出 InvalidOperationException?
- python - Discord Webhook 编辑请求返回 400(错误请求)
- python - 如何按四分位数对 pandas 中的值进行分组并获取其他列的指标?
- excel - 单击主工作表上的超链接以过滤第二张工作表上的数据 - Excel VBA
- vue.js - 在 Ionic Vue.js 组件中使用 cordova 插件
- ruby-on-rails - Ruby on Rails,仅在新操作时禁用表单中的文本字段
- express - 将 ServiceMonitor 添加到未在 Prometheus 中注册的现有 Express 微服务中