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.