简体   繁体   中英

Optimize PNG image sequence animation

I have a PNG sequence that form an animation, and I use this function to play:

HTML:

<script>
    $(document).ready(function () {
        playAnimation("firstAnimation", 58); // 58 images in one sequence
    });
</script>

<img id="firstAnimation" directoryimage='../myFirstAnimation/' />

JS/JQUERY:

var animation_list = [];

    function playAnimation(elementID, limitCount, count = 0) {
        var directoryimage = $(`#${elementID}`).attr('directoryimage');

        if (animation_list.find(x => x.name == $(`#${elementID}`).attr('id')) == undefined) {
            animation_list.push({
                name: $(`#${elementID}`).attr('id'), animation: setInterval(function () {
                    count++;
                    $(`#${elementID}`).attr('src', directoryimage + count + ".png");

                    if (count == limitCount) {
                        count = 0;
                    }
                }, 30)
            });
        }
    }

The problem is that for the animation to run at "60 FPS" I put 30 milliseconds in setInterval and is always prompted to get the image.

So my question is, how can I cache this animation, or find another way to optimize

If you need to run the animation at 60 FPS, then your best bet would be switching to animated GIF (that also supports transparency). The problem with playing it frame-by-frame is highly unpredictable loading times for each individual PNG "frame" so combining them in a GIF would allow you to preload the entire "video" at once and then just play it. This is by far the easiest option as you would not need to worry about caching each frame.

If GIF is not an option, then you will need to preload all the frames beforehand (either in a script placed in the <head> or otherwise), so that they are all cached and the <img> element does not need to waste time loading them one by one. Once preloaded, the playback JavaScript function will flip the frames much same way you are doing now.

Hope that helps!

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