最終效果如下:

動畫分成兩步
制定運行軌跡
我們先要畫一條底部的淡藍色半透明路勁做為能量流動的管道
這里用SVG的path去做(其實這里可以直接用背景圖), 代碼如下:
<!-- 代碼是用react寫的, 刪除了遍歷以及部分代碼 -->
<svg>
<!-- 工具描述提示符,被用在fill里做過濾等操作,這里是小球底部的發光 -->
<defs>
<radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style={{ stopColor: "rgba(2,246,255,.5)" }} />
<stop offset="100%" style={{ stopColor: "rgba(2,246,255,0)" }} />
</radialGradient>
</defs>
<!-- 這里遍歷N個淡藍色線條路徑 d為路徑-->
<path d={item.path} stroke="rgba(29,159,167,0.4)" fill="transparent" strokeWidth={5}></path>
...
<!-- 這里是發光小球 通過兩個圓疊加形成 -->
<g>
<circle cx={cx} cy={cy} r="15" fill="url(#grad1)"></circle>
<circle cx={cx} cy={cy} r="5" fill="rgba(2,246,255)"></circle>
</g>
</svg>
創建DOM并按照軌跡動畫
這里的核心原理通過offset-path這個屬性設置運動偏移路徑,再通過offset-distance來設置偏移量,這樣通過css3 animation就可以讓元素按照一定的軌跡運動
<!-- 這里要保證盒子跟SVG的盒子位置重合,寬高一致,這樣路徑點才能一致 -->
<div className={styles.animate}>
<!-- 這里遍歷N個div,讓每一個div都按照offsetPath也就是svg內path的d的值進行流動 -->
<!-- animationDelay 負數表示渲染前就已經執行, 渲染時就可以鋪滿整個路徑 -->
<div key={index} className={styles.point3} style={{ "offsetPath": "path('M 105 34 L 5 34')", "animationDelay": `-${index * 1}s`, "animationDuration": '5s', 'animationPlayState': `${stop ? 'paused' : 'running'}` }}></div>
...
</div>
.point3 {
width: 10px;
height: 2px;
// offset-path: path('M 248 108 L 248 172 L 1510 172');
offset-distance: 0%;
animation: flow 20s linear normal infinite;
background-image: linear-gradient(to right, rgba(255, 255, 255, 0) 10%, #FEFE02);
position: absolute;
left: 0;
right: 0;
}
}
@keyframes flow {
from {
offset-distance: 0%;
}
to {
offset-distance: 100%;
}
}
到此這篇關于css animation配合SVG制作能量流動效果的文章就介紹到這了,更多相關css animation配合SVG內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章,希望大家以后多多支持腳本之家!