likes
comments
collection
share

使用offset-path实现自定义路径动画

作者站长头像
站长
· 阅读数 32

很多时候美工提供的效果图,对某个点的运动轨迹并不是一个常规直线,这时候可以使用offset-path实现点的运动轨迹。

例如这张图里,要实现绿色点沿着红色曲线运动。使用offset-path实现自定义路径动画html部分

<div class="move-box">
   <div class="dot"></div>
</div>

css部分

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

.move-box{
    width: 80%;
    height: 1000px;
    margin: 50px auto;
    border: 1px solid black;
    position: relative;
    /*背景图只是用来演示运动轨迹是否正确*/
    background: url(files/leaf.png) no-repeat left top;
}
.dot{
    position: absolute;
    left: 38px;
    top: 104px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: green;
    box-shadow: 0 0 20px green;
    offset-path: path("M44.500,162.500 C44.500,162.500 89.756,180.432 135.500,145.500 C181.244,110.568 188.925,108.900 199.500,73.500 C210.075,38.100 204.689,3.134 270.500,17.500 C336.311,31.866 405.804,-10.398 429.500,4.500 C453.196,19.398 510.841,47.341 531.500,73.500 C552.159,99.659 529.723,58.407 602.500,31.500 C675.277,4.593 692.423,6.276 704.500,40.500 C716.577,74.724 710.319,92.353 711.500,122.500 C712.681,152.647 689.619,223.416 680.500,260.500 C671.381,297.584 529.438,204.141 559.500,324.500 C589.562,444.859 503.852,697.103 614.500,521.500 C725.148,345.897 681.020,258.038 717.500,319.500 C753.980,380.962 779.594,527.618 702.500,596.500 C625.406,665.382 412.897,742.971 378.500,639.500 C344.103,536.029 401.155,541.987 422.500,415.500 C443.845,289.013 370.529,186.899 485.500,172.500 C600.471,158.101 688.010,121.886 634.500,113.500 C580.990,105.114 610.507,137.029 492.500,112.500 C374.493,87.971 364.275,43.495 312.500,119.500 C260.725,195.505 225.342,182.297 165.500,301.500 C105.658,420.703 110.850,569.542 61.500,548.500 C12.150,527.458 44.798,372.481 12.500,317.500 C-19.798,262.519 26.643,163.161 44.500,162.500 Z");
    animation: move 30s linear infinite;
}

这里需要注意的是:

  1. .dotlefttop的值,是当前点的位置相对于运动轨迹最左侧最顶部的位置;
  2. 无论.dot的尺寸如何,它的运动相对位置是物体的中心点,所以不需要对.dot做居中的偏移。
  3. offset-path的值的获取有多种方法,考虑到各种ps版本的问题,比较靠谱的办法是:用钢笔工具勾出路径,然后“文件 - 导出 - 路径到Illustrator”,存为.ai格式,在illustrator里保存为svg,记事本打开这个svg文件。offset-path的值即为svgpath的值。当然,这个交给美工来做就可以了,他们比较熟练。使用offset-path实现自定义路径动画