前端如何实现飞线图?

7,260 阅读2分钟

效果如下

飞线图.gif

UI设计了这么一个设计稿,这个好做,直接切一个gif给我,我定位就行了。
但是前端也能实现。

流程

1、显示svg

<svg width="400" height="600">
  <path d="M41 236 C65 118 244 112 213 327 L176 341 123 529 74 342 37 325 Z" stroke="#333" stroke-width="2" fill="none" />
</svg>

image.png

2、画一个点跑起来

html

<div class="line-panel">
  <div class="round-1"></div>
  <svg width="400" height="600">
    <path d="M41 236 C65 118 244 112 213 327 L176 341 123 529 74 342 37 325 Z" stroke="#333" stroke-width="2" fill="none" />
  </svg>
</div>

scss

说明一下下面animation的属性含义CSS animation 属性

animation: move 3s 0s linear infinite;

  • move: 是@keyframes定义的移动方法
  • 3s: 跑完svg路径要花的时间
  • 0s: 延迟多久后开始执行
  • linear: 线性
  • infinite: 无限循环执行
.line-panel {
  //圆点
  .round-1 {
    z-index: 2;
    position: absolute;
    left: 0;
    border-radius: 50%;
    background-color: red;
    width: 10px;
    height: 10px;
    //移动,这里的path跟svg的path一样
    offset-path: path('M41 236 C65 118 244 112 213 327 L176 341 123 529 74 342 37 325 Z');
    animation: move 3s 0s linear infinite; //含义上面有注释
  }
  //svg定位一下
  svg{
    position: absolute;
    left: 0;
  }
}
//移动动画
@keyframes move {
  100% {
    offset-distance: 100%;
  }
}

效果

De9Zrxyyof.gif

3、多个点实现

万一有很多个点呢,我们可以用scss@mixin来做优化

html

  • 我们加5个点移动
<div class="line-panel">
  <div class="round-1"></div>
  <div class="round-2"></div>
  <div class="round-3"></div>
  <div class="round-4"></div>
  <div class="round-5"></div>
  <svg width="400" height="600">
    <path d="M41 236 C65 118 244 112 213 327 L176 341 123 529 74 342 37 325 Z" stroke="#333" stroke-width="2" fill="none" />
  </svg>
</div>

scss

  //统一原点的路径,和动画时间
  $svg-path: "M41 236 C65 118 244 112 213 327 L176 341 123 529 74 342 37 325 Z"; //此path对应svg内的path
  /*
     $color: 圆点背景颜色
     $path: 圆点行走路径
     $duration跑完需要多久时间
     $delay延迟多久开始跑
   */
  @mixin move-round($color, $path, $duration, $delay) {
    z-index: 2;
    position: absolute;
    left: 0;
    border-radius: 50%;
    background-color: $color;
    width: 10px;
    height: 10px;
    //移动
    offset-path: path($path);
    animation: move $duration $delay linear infinite;
  }
  .line-panel {
    .round-1 {
      @include move-round(blue, $svg-path, 5s, 0s);
    }
    .round-2 {
      @include move-round(green, $svg-path, 5s, 1s);
    }
    .round-3 {
      @include move-round(red, $svg-path, 5s, 2s);
    }
    .round-4 {
       @include move-round(black, $svg-path, 5s, 3s);
     }
    .round-5 {
      @include move-round(yellow, $svg-path, 5s, 4s);
    }

    svg{
      position: absolute;
      left: 0;
    }
  }

  @keyframes move {
    100% {
      offset-distance: 100%;
    }
  }

效果

0V9Y9vcqJ9.gif

参考