Improve HTML5 Canvas frame by frame JPG animation to fully cache before animating

ε祈祈猫儿з 提交于 2019-12-03 09:11:12

This is a modified version of your draw function which preloads all images before putting them on a canvas.

It assumes you have a canvas with id 'anim' (as there is no reference of the canvas in the source you provided)

<canvas id='anim' width='660' height='500'></canvas>

JavaScript: (tested on an iPad)

function draw() {
    var ctx = document.getElementById('anim').getContext("2d");
    var start = 1, stop = 121,cur=start,imgArr=[];

    var loadLoop = function() {
        var img = document.createElement("img");
        img.onload = function() {
            imgArr.push(this);
            cur++;

            if(cur > stop) {
                // all images preloaded
                animate();
            }
            else {
                loadLoop();
            }
        }

        img.src = "jpg_80/t5_"+(cur)+".jpg";
    }

    loadLoop();

    function animate() {
        var timer = setInterval(function() {
            ctx.drawImage(imgArr.shift(), 0, 0 );
            if(imgArr.length == 0) {
                // no more frames
                clearInterval(timer);
            }
        },1000/24);
    }
}

You can create 121 <img> elements and add an .onload function to each of them. In that handler you increment a number, and when it reaches 121, you start the animation.

But what you are trying to do sounds like you want to create a video clip. When that's your intention, the <video> tag might be a better solution. A 121 frame video clip encoded with a modern codec will be much smaller than 121 separate JPEGs, because video compression algorithms use redundancies between frames to improve compression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!