在HTML5 Canvas上预加载图像序列

时间:2014-03-14 17:33:41

标签: html5 image canvas preload smooth

我有这个动画,我在5880ms显示143张图像。问题是动画运行不顺畅,我认为必须要在画布上预加载这些图像。

以下是代码:

//Request animation standarization for all browsers
var getRequestAnimationFrame = function () {
   return window.requestAnimationFrame ||
       window.webkitRequestAnimationFrame ||
       window.mozRequestAnimationFrame ||
       window.oRequestAnimationFrame ||
       window.msRequestAnimationFrame ||
       function ( callback ){
            window.setTimeout(enroute, 1000/41);
            //41 fps
       };
};


setTimeout(function(){

    var imgNumber = 1;
var lastImgNumber = 143;

var canvas = document.getElementById('utn');    
var ctx = canvas.getContext('2d');

var img = new Image;
img.onload = function(){
       ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
   ctx.drawImage( img, 0, 0 );
 };

var fpAnimationFrame = getRequestAnimationFrame();
var timer = function(){
    if (imgNumber>lastImgNumber){
        clearInterval( timer );
    }else{
            img.src = "img/utn_"+( imgNumber++ )+".png";
        fpAnimationFrame(timer);
      }
    };
fpAnimationFrame(timer); //Call animation the first time    
}, 6180); //the animation starts at 6.18s

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

是的,也许您需要预先加载所有图像,然后显示序列。您需要使用图像预加载器,您可以在此网站上找到多个预加载器。 http://www.jqueryrain.com/demo/jquery-preloader-image/page/2/