如何制作动漫每个SVG

时间:2019-05-27 15:17:12

标签: javascript jquery html svg anime.js

现在,我的代码动画只有一个SVG,并且页面中有很多路径,但是我希望为页面中的每个SVG动画。如果我的页面中有很多SVG,则只有第一个SVG动画。

我暂时在本地主机上工作

''脚本

{
    class MorphingBG {
        constructor(el) {
            this.DOM = {};
            this.DOM.el = el;
            this.DOM.paths = Array.from(this.DOM.el.querySelectorAll('path'));
            this.animate();
        }
        animate() {
            this.DOM.paths.forEach((path) => {
                setTimeout(() => {
                    anime({
                        targets: path,
                        duration: anime.random(3000,5000),
                        easing: [0.5,0,0.5,1],
                        d: path.getAttribute('pathdata:id'),
                        loop: true,
                        direction: 'alternate'
                    });
                }, anime.random(0,1000));
            });
        }
    };

    new MorphingBG(document.querySelector('.svg-morph'));
};

''html

<svg class="svg-morph morph-1" viewBox="0 0 963 754">
<path d="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,56.6,133.8,61,201.5c15.1,233.2-6.4,205.1-49.5,314 C-69,811,459,815,457.4,632c2.2-161.1,601.7-37.1,635.9-382.5C1124.6-66.8,915.2-218.7,739.8-218.7 Z" pathdata:id="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,18,28,20,170c3,228-3,125-8.5,345.5C8,763,379.34,770,551.34,622 c140-157,502.46,60.4,536.66-285C1119.3,20.7,915.2-218.7,739.8-218.7 Z"></path>
</svg>

<svg class="svg-morph morph-2" version="1.1" viewBox="0 0 735.6 807">
    <path d="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,56.6,133.8,61,201.5c15.1,233.2-6.4,205.1-49.5,314 C-69,811,459,815,457.4,632c2.2-161.1,601.7-37.1,635.9-382.5C1124.6-66.8,915.2-218.7,739.8-218.7 Z" pathdata:id="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,18,28,20,170c3,228-3,125-8.5,345.5C8,763,379.34,770,551.34,622 c140-157,502.46,60.4,536.66-285C1119.3,20.7,915.2-218.7,739.8-218.7 Z"></path>
</svg>

目前只有svg class =“ svg-morph morph-1”具有动画效果

1 个答案:

答案 0 :(得分:0)

只需替换此行:

new MorphingBG(document.querySelector('.svg-morph'));

使用以下代码:

// get all elements that you want to morph (not only one)
let toBeMorphed = document.querySelectorAll('.svg-morph');

// apply the MorphingOperator on each of these elements
toBeMorphed.forEach(function(svg) {
    new MorphingBG(svg);
});