画虚线

676 阅读2分钟

svg

stroke-dasharray

一个参数时

表示虚线长度和每段虚线之间的间距 参考文章

  • 如:stroke-dasharray = '10' 表示:虚线长10,间距10,然后重复 虚线长10,间距10

两个参数或者多个参数时

一个表示长度,一个表示间距

  • 如:stroke-dasharray = '10, 5' 表示:虚线长10,间距5,然后重复 虚线长10,间距5
  • 如:stroke-dasharray = '8, 3, 3, 3' 表示:虚线长8,间距3,虚线长3,间距3,之后开始如此循环
stroke-dasharray = '10'
stroke-dasharray = '10, 5'
stroke-dasharray = '8, 3, 3, 3'

image.png

stroke-dashoffset

相对于起始点的偏移 MDN参考

正数偏移x值的时候,相当于往左移动了x个长度单位;负数偏移x的时候,相当于往右移动了x个长度单位。

  • 需要注意的是,不管偏移的方向是哪边,要记得dasharray 是循环的,也就是 虚线-间隔-虚线-间隔。

  • 这个属性要搭配stroke-dasharray才能看得出来效果,非虚线的话,是无法看出偏移的。

1. 不是虚线,偏移没有效果
stroke-dasharray="0" 

2. 虚线没有设置偏移
stroke-dasharray="3 1"
stroke-dashoffset="0"

3. 偏移正数,虚线整体左移了3个单位
// 图中3后面的红线段,就是起始线段,线段之后是1个单位的间隔,我们可见区域从这个间隔开始,然后循环 3-1,3-1的虚线-间隔-虚线-间隔
stroke-dashoffset="3"

4. 偏移负数,虚线整体右移动了3个单位
// 由于dasharray 是循环的,前面偏移的位置会有dasharray 填充上
stroke-dashoffset="-3"

5. 偏移正数,虚线整体左移了1个单位
// 最终呈现出来的效果跟 线段4 一样
stroke-dashoffset="1"

效果如图<红线段是偏移的距离>

image.png

canvas

ctx.setLineDash(pattern)设置虚线

export function drawLine(id) {
  // canvas元素
  const canvas = document.getElementById(id);
  // context对象
  const ctx = canvas.getContext('2d');
  let y = 15;
  function drawDashedLine(pattern) {
    ctx.beginPath();
    ctx.setLineDash(pattern);
    ctx.moveTo(0, y);
    ctx.lineTo(25, y);
    ctx.stroke();
    y += 24;
  }

  drawDashedLine([]);
  drawDashedLine([1, 1]);
  drawDashedLine([10, 5]);
  drawDashedLine([8, 3, 3, 3]);
}

echarts

lineStyle属性

lineStyle:{ 
    type: [5, 10], 
    dashOffset: 5 
}