首页 > 解决方案 > How to anime EACH svg

问题描述

Now my code anime only one SVG with many path in my page, but I would like anime each SVG in my page. If I have many SVG in my page, only first SVG anime.

I work on my localhost for the moment

''script

{
    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>

For the moment only svg class="svg-morph morph-1" it's animate

标签: javascriptjqueryhtmlsvganime.js

解决方案


只需替换这一行:

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);
});

推荐阅读