Animated Image with Javascript

后端 未结 2 1520
北恋
北恋 2020-12-08 06:06

Is there a way to create a gif like image with javascript based on some png or jpg?

Just a simple code that change one image for another, creating the impression of

2条回答
  •  猫巷女王i
    2020-12-08 06:29

    Stackoverflow used this technique for its unicorn animations last april fools day. I preserved the animations on my website. The animation code is my own - I didn't look at how stackoverflow was doing it.

    The concept is to create a sprite, and then change the background position on an interval.


    (source: jumpingfishes.com)

    #animation {
        background-image: url(charging.png);
        background-repeat: no-repeat;
        height: 102px;
        width: 140px;
    }
    
    function startAnimation() {
        var frameHeight = 102;
        var frames = 15;
        var frame = 0;
        var div = document.getElementById("animation");
        setInterval(function () {
            var frameOffset = (++frame % frames) * -frameHeight;
            div.style.backgroundPosition = "0px " + frameOffset + "px";
        }, 100);
    }
    

    Working demo: http://jsfiddle.net/twTab/

    Edit: If you don't want to create a sprite, here's an alternate technique you can use. Put all of your animation frame images in a div and hide all but the first one. In your setInterval function, move the first image to the end of the list:

    #animation img {
        display: none;
    }
    #animation img:first-child {
        display: block;
    }
    
    function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInterval(function () { frames[i % frameCount].style.display = "none"; frames[++i % frameCount].style.display = "block"; }, 100); }

    Working demo: http://jsfiddle.net/twTab/3/

提交回复
热议问题