美文网首页优美编程Web前端之路
前端碰撞室之搞懂stroke-dasharray和stroke-

前端碰撞室之搞懂stroke-dasharray和stroke-

作者: 小遁哥 | 来源:发表于2020-03-23 16:47 被阅读0次
    <div
      style="width:600px; margin:0 auto;box-shadow:0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);"
    >
      <svg width="100%" height="100%" viewBox="0 0 400 400">
        <line
          x1="0"
          y1="10"
          x2="400"
          y2="10"
          stroke-width="10"
          stroke="red"
        ></line>
      </svg>
    </div>

效果如下


image.png

stroke-dashaharray

加上stroke-dashaharray = "20"


等同于 stroke-dashaharray = "20 20",画20像素的线段,间距20像素,画20像素线段 ...
加上stroke-dashaharray = "20 10 30"

等同于 stroke-dashaharray = "20 10 30 20 10 30", 画20像素的线段,间距10像素,画30像素的线段,间距20像素,画10像素的线段,间距30像素,画20像素的线段...
所以当stroke-dashaharray = "400" 时效果和不加是一样的 ,但是红色线段后面是400像素的间距

stroke-dashoffset

stroke-dashoffset 只作用于一次,正值时相当于往左拉,当stroke-dashoffset = "60"


结合这个特性,初始时stroke-dashoffset = 400,显示的是第一个线段后面的间距部分,鼠标悬浮后,使得stroke-dashoffset 为0,就得到了从左往右的动画
    <div class="parent">
      <svg width="100%" height="100%" viewBox="0 0 400 400">
        <line
          class="line"
          x1="0"
          y1="10"
          x2="400"
          y2="10"
          stroke-dasharray="400"
          stroke-dashoffset="400"
          stroke-width="10"
          stroke="red"
        ></line>
      </svg>
    </div>

  .parent {
    width: 600px;
    margin: 0 auto;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12),
      0 3px 1px -2px rgba(0, 0, 0, 0.2);
    .line {
      transition: stroke-dashoffset 0.35s ease-out;
    }
    &:hover {
      .line {
        stroke-dashoffset: 0;
      }
    }
  }

从右往左,只需要stroke-dashoffset: 800;,0的时候是显示当前间距前面的线段,800是显示当前间距后面的线段。
作用到圆上道理也是一样的

打勾动画
SVG圆环动画

相关文章

网友评论

    本文标题:前端碰撞室之搞懂stroke-dasharray和stroke-

    本文链接:https://www.haomeiwen.com/subject/urkwyhtx.html