morphTo()
通过将 morphTo()
函数传递给 SVGPathElement
的 d
属性或 SVGPolylineElement
或 SVGPolygonElement
的 points
属性,从一个 SVG 形状创建变形动画到另一个 SVG 形状。
可以设置可选的 precision
参数来配置生成用于变形两个形状的点数。
如果 precision 参数设置为 0
,则不会生成点外推。
svg.morphTo(shapeTarget, precision);
参数
名称 | 接受 |
---|---|
shapeTarget | CSS 选择器 | SVGPathElement | SVGPolylineElement | SVGPolygonElement |
precision=.33 (可选) | 介于 0 和 1 之间的 Number |
返回
一个 Array
,包含形状的起始和最终 String
值
morphTo() 代码示例
import { animate, svg, utils } from 'animejs';
const [ $path1, $path2 ] = utils.$('polygon');
function animateRandomPoints() {
// Update the points attribute on #path-2
utils.set($path2, { points: generatePoints() });
// Morph the points of #path-1 into #path-2
animate($path1, {
points: svg.morphTo($path2),
ease: 'inOutCirc',
duration: 500,
onComplete: animateRandomPoints
});
}
// Start the animation
animateRandomPoints();
// A function to generate random points on #path-2 on each iteration
// For demo purpose only
function generatePoints() {
const total = utils.random(4, 64);
const r1 = utils.random(4, 56);
const r2 = 56;
const isOdd = n => n % 2;
let points = '';
for (let i = 0, l = isOdd(total) ? total + 1 : total; i < l; i++) {
const r = isOdd(i) ? r1 : r2;
const a = (2 * Math.PI * i / l) - Math.PI / 2;
const x = 152 + utils.round(r * Math.cos(a), 0);
const y = 56 + utils.round(r * Math.sin(a), 0);
points += `${x},${y} `;
}
return points;
}
<svg viewBox="0 0 304 112">
<g stroke-width="2" stroke="currentColor" stroke-linejoin="round" fill="none" fill-rule="evenodd">
<polygon id="path-1" points="152,4 170,38 204,56 170,74 152,108 134,74 100,56 134,38"></polygon>
<polygon style="opacity: 0" id="path-2" points="152,4 170,38 204,56 170,74 152,108 134,74 100,56 134,38"></polygon>
</g>
</svg>