嘗試使用 Svg 實現(xiàn)簡易的動畫效果。有關 Svg 的具體知識點不在此文贅述,僅就所舉示例的需求點闡述實現(xiàn)思路。
先闡明具體需求:白色軌跡需自起始點旋轉(zhuǎn)至由用戶成長值決定的終點。

動畫效果如下:若無效果請戳這里。
該動畫可拆分為兩部分實現(xiàn):粉紅圓環(huán)軌跡、粉紅圓形尾巴。
繪制粉紅圓環(huán)軌跡
相關代碼:
<path d="M 110 10 a 100 100 0 0 1 0 200 a 100 100 0 0 1 0 -200 Z" fill="none" stroke="#FD7991" stroke-width="4" stroke-linecap="round" stroke-dasharray="628.4073486328125">
<animate attributeName="stroke-dashoffset" from="628.4073486328125" to="0" dur="2s" repeatCount="indefinite" />
</path>
使用 path 繪制半徑 100 的圓環(huán)軌跡。起點 M 110 10,右半圓弧 a 100 100 0 0 1 0 200,左半圓弧 a 100 100 0 0 1 0 -200,閉合路徑 Z。
不了解 Svg Paths 的同學建議自行科普~
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
S = smooth curveto
Q = quadratic Belzier curve
T = smooth quadratic Belzier curveto
A = elliptical Arc
Z = closepath
可優(yōu)先了解 圓弧 A a:
A rx ry x-axis-rotation large-arc-flag sweep-flag x y
a rx ry x-axis-rotation large-arc-flag sweep-flag dx dy
路徑繪制完畢如何添加描線效果呢?請注意 stroke-dasharray 及 stroke-dashoffset。
屬性 stroke-dasharray 控制描邊點劃線的圖案范式;屬性 stroke-dashoffset 指定 dash 模式至路徑開始的距離。
當 stroke-dashoffset 偏移量為 path 路徑長度時,粉紅軌跡完全不可見,逐步減小偏移至 0 可使之完全呈現(xiàn)。
這好比在熱狗上擠果醬,本應從其左側(cè)擠至右側(cè)。而你卻從其右側(cè)開始向右擠,整整偏移了一條熱狗的長度。熱狗上無半點果醬,只能靠減小偏移來加料嘍。
指定 stroke-dasharray 為 path 路徑長度,意味著操作空間為整條熱狗。

友情提示如何獲取路徑長度:
var pathLength = $('path')[0].getTotalLength();
繪制粉紅圓形尾巴
尾巴可使用圖片繪制:
<defs>
<pattern id="tail" width="100%" height="100%" patternContentUnits="objectBoundingBox">
<image width="1" height="1" xlink: />
</pattern>
</defs>
<g>
<circle cx="0" cy="0" r="8" fill="url(#tail)"></circle>
</g>
也可使用漸變繪制:
<defs>
<radialGradient cx="50%" cy="50%" fx="50%" fy="50%" r="60%" id="tail">
<stop stop-opacity="1" stop-color="#FD7991" offset="30%"/>
<stop stop-opacity="0.5" stop-color="#fD97AA" offset="40%"/>
<stop stop-opacity="0" stop-color="#FECBD4" offset="80%"/>
</radialGradient>
</defs>
<g>
<rect x="-10" y="-10" width="20" height="20" fill="url(#tail)"></rect>
</g>
為尾巴添加動畫:
<rect x="-10" y="-10" width="20" height="20" fill="url(#tail)">
<animateMotion path="M 110 10 a 100 100 0 0 1 0 200 a 100 100 0 0 1 0 -200 Z" rotate="auto" dur="2s" repeatCount="indefinite" />
</rect>
動畫路徑、執(zhí)行時間、速度曲線等屬性與粉紅圓環(huán)軌跡保持一致即可~
控制動畫終止位置
再次闡明具體需求:白色軌跡需自起始點旋轉(zhuǎn)至由用戶成長值決定的終點。
假定軌跡描線長度占圓環(huán)總長的百分比已知,如何控制動畫終止位置?根據(jù)百分比計算描線長度然后巴拉巴拉計算坐標點...數(shù)學欠佳的還是繞行吧。
控制動畫執(zhí)行次數(shù) repeatDur 便可...
var totalTime = 3;
var percent = 0.8;
var runAnimate = function () {
var durTime = totalTime * percent;
$circleAnimate[0].setAttribute('repeatDur', durTime + 's');
$tailAnimate[0].setAttribute('repeatDur', durTime + 's');
$circleAnimate[0].beginElement();
$tailAnimate[0].beginElement();
};
作者:呆戀小喵
我的后花園:https://sunmengyuan.github.io/garden/
我的 github:https://github.com/sunmengyuan
原文鏈接:https://sunmengyuan.github.io/garden/2017/11/16/svg-comet.html