Pasition - Path Transition with little JS code, render to anywhere - 超小尺寸的Path過渡動畫類庫git
最近和貝塞爾曲線槓上了,如curvejs 和 pasition 都是貝塞爾曲線的應用案例,將來還有一款和貝塞爾曲線相關的開源的東西,暫時保密。github
npm install pasition
CDN地址下載下來使用:web
https://unpkg.com/pasition@1.0.0/dist/pasition.jsnpm
你能夠經過 pasition.lerp
方法拿到插值中的shapes:canvas
var shapes = pasition.lerp(pathA, pathB, 0.5) //拿到shapes以後你能夠在任何你想要渲染的地方繪製,如canvas、svg、webgl等 ...
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命令:svg
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){ } });
對上面傳入的配置項目一一解釋下:工具
在progress裏能夠拿到path轉變過程當中的shapes和運動進度percent(範圍是0-1)。下面來看看shapes的結構:動畫
[ [ [], //curve [], //curve [] //curve ], //shape [[],[],[],[],[]], //shape [[],[],[],[],[]] //shape ]
在開發者工具裏截圖:
每條curve都包含8個數字,分別表明三次貝塞爾曲線的 起點 控制點 控制點 終點。
每一個shape都是閉合的,因此shape的基本規則是:
知道基本規則以後,咱們能夠進行渲染,這裏拿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就能夠了。
https://github.com/AlloyTeam/pasition
This content is released under the MIT License.