morphTo()
通过将 SVGPathElement
的 d
属性,或 SVGPolylineElement
或 SVGPolygonElement
的 points
属性传递给 svg.morphTo()
,可创建从一个 SVG 形状到另一个形状的变形动画。
可以设置一个可选的 precision
参数,用于配置在两个形状之间变形时生成的点数量。
如果 precision
参数设置为 0
,则不会进行点外推。
svg.morphTo(shapeTarget, precision);
参数
名称 | 接受 |
---|---|
shapeTarget | CSS 选择器 | SVGPathElement | SVGPolylineElement | SVGPolygonElement |
precision=.33 (可选) | 一个介于 0 和 1 之间的 Number 类型值 |
返回
一个包含形状的起始和最终 String
值的 Array
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>