使用 pasition 製作酷炫Path過渡動畫

點擊右上方紅色按鈕關注“web秀”,讓你真正秀起來

使用 pasition 製作酷炫Path過渡動畫

使用 pasition 製作酷炫Path過渡動畫

pasition

Pasition – Path Transition with little JS code, render to anywhere – 超小尺寸的Path過渡動畫類庫 Github源代碼 在線演示 最近和貝塞爾曲線槓上了,如curvejs 和 pasition 都是貝塞爾曲線的應用案例,未來還有一款和貝塞爾曲線相關的開源的東西,暫時保密。

安裝

npm install pasition

CDN地址下載下來使用: https://unpkg.com/[email protected]/dist/pasition.js

使用指南

pasition.lerp

你可以通過 pasition.lerp 方法拿到插值中的shapes:

var shapes = pasition.lerp(pathA, pathB, 0.5)
//拿到shapes之後你可以在任何你想要渲染的地方繪製,如canvas、svg、webgl等
...

pasition.animate

pasition.animate({
from : fromPath,
to : toPath,
time : time,
easing : function(){ },
begin :function(shapes){ },
progress : function(shapes, percent){ },
end : function(shapes){ }
})

path從哪裡來?你可以從svg的path的d屬性獲取。 支持所有的SVG Path命令:

M/m = moveto
L/l = lineto
H/h = horizontal lineto
V/v = vertical lineto
C/c = curveto
S/s = smooth curveto
A/a = elliptical Arc
Z/z = closepath
Q/q = quadratic Belzier curve
T/t = smooth quadratic Belzier curveto

舉個例子:

pasition.animate({
from: 'M 40 40 Q 60 80 80 40T 120 40 T 160 40 z',
to: 'M32,0C14.4,0,0,14.4,0,32s14.3,32,32,32 s32-14.3,32-32S49.7,0,32,0z',
time: 1000,
easing : function(){ },
begin:function(shapes){ },
progress : function(shapes, percent){
//你可以在任何你想繪製的地方繪製,如canvas、svg、webgl
},
end : function(shapes){ }
});

對上面傳入的配置項目一一解釋下: 1. from 起始的路徑 2. to 終點的路徑 3. time 從from到to所需要的時間 4. easing 緩動函數(不填默認是勻速運動) 5. begin 開始運動的回調函數 6. progress 運動過程中的回調函數 7. end 運動結束的回調函數 在progress裡可以拿到path轉變過程中的shapes和運動進度percent(範圍是0-1)。下面來看看shapes的結構:

[
[
[], //curve
[], //curve
[] //curve
], //shape
[[],[],[],[],[]], //shape
[[],[],[],[],[]] //shape
]

在開發者工具裡截圖:

每條curve都包含8個數字,分別代表三次貝塞爾曲線的 起點 控制點 控制點 終點。

每個shape都是閉合的,所以shape的基本規則是: 1. 每條curve的終點就是下一條curve的起點 2. 最後一條curve的終點就是第一條curve的起點 知道基本規則之後,我們可以進行渲染,這裡拿canvas裡渲染為例子: Fill模式:

function renderShapes(context, curves, color){
context.beginPath();
context.fillStyle = color||'black';
context.moveTo(curves[0][0], curves[0][1]);
curves.forEach(function(points){
context.bezierCurveTo(points[2], points[3], points[4], points[5], points[6], points[7]);
})
context.closePath();
context.fill();
}
shapes.forEach(function(curves){
renderShapes(context,curves,"#006DF0")
})

Stroke模式:

function renderCurve(context, points, color){
context.beginPath();
context.strokeStyle = color||'black';
context.moveTo(points[0], points[1]);

context.bezierCurveTo(points[2], points[3], points[4], points[5], points[6], points[7]);
context.stroke();
}
shapes.forEach(function(curves){
curves.forEach(function (curve) {
renderCurve(context, curve, "#006DF0")
})
})

當然你也可以把shapes轉成SVG的命令在SVG渲染,這應該不是什麼困難的事情:

 function toSVGPath(shapes){
//把 shapes數組轉成 M....C........C........Z M....C.....C....C...Z 的字符串。
}

這個函數可以自行嘗試一下,生成出的字符串賦值給SVG的Path的d就可以了。

公告


分享到:


相關文章: