简体   繁体   中英

Best way to use svg animating library vivus with intersection observer

I use vivus.js to animate SVGs. I wonder what is the best way to use it in combination with intersection observer, concerning performance.

On my page are several sections, including inline svgs. These svgs should be animated when scrolling down the page, stop when leaving the viewport und start again when the container is observed again.

It works but i am not sure if this is the best way to build vivus objects und play them again and again in this way. These solution seems to crash firefox performance..

I welcome all comments, suggestions and proposed improvements.

$( document ).ready(function() {
    //Define observed Items
    var myItems = document.querySelectorAll(".observed-item");

    //Define observer Options
    var observeroptions = {
        root: null,
        rootMargin: "-35% 0% -35% 0%",
        threshold: 0,
    };

    //Create new Observer Object
    var observer = new IntersectionObserver(function(entries, observer){
        entries.forEach(function(entry){

//Define Index Variable
var myIndex = $(entry.target).index();


var myvivus = new Vivus("item-svg" + myIndex, {
                    duration: 150,
                    start: 'manual'
                },
                function () {
                   $(entry.target).addClass('callback-item-animation');
                }
            )


            if (entry.intersectionRatio > 0) {

                //Add class to Entry Target
                $(entry.target).addClass("item-animate");
                myvivus.reset().play();

} else {
//Remove animated Class from observed Item
                $(entry.target).removeClass("item-animate");
                myvivus.stop().reset();

            }

        });
    },observeroptions);

    myItems.forEach(function(myItem) {
        observer.observe(myItem);
    });

});

I created a pen:

https://codepen.io/Milenoi/pen/JBxgOG

Please Note: without Polyfill works in Chrome + Firefox

As you can see, the animation doesn't work as expected, the svg animation should stop when leaving observer and start again wenn element is intersected again..

Your hoisting observer and clashing it in the function. Add var or let before observer =, then change the name of observer in that function to something unique. Also qualify everything with window. Or context. That should improve the performance marginally

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM