How do you deal with html5's canvas image load asynchrony?

前端 未结 2 1890
盖世英雄少女心
盖世英雄少女心 2020-12-16 08:29

I\'ve been learning about html5\'s canvas. Because images can take a while to load, it seems the appropriate technique is to use onload to wait for the image t

2条回答
  •  星月不相逢
    2020-12-16 09:00

    Pre-load your images before working with the canvas. Put all your image urls into an array, loop through the array creating new images, and when they are all loaded call a function that will start your canvas work.

    Following snippet uses the native JS Promises, but if supporting older browsers that do not have native Promise you can use Q or jQuery libraries in a similar fashion

    var images = ['imageurl.jpg','imageurl2.jpg','imageurl3.jpg'];
    var loadedImages = {};
    var promiseArray = images.map(function(imgurl){
       var prom = new Promise(function(resolve,reject){
           var img = new Image();
           img.onload = function(){
               loadedImages[imgurl] = img;
               resolve();
           };
           img.src = imgurl;
       });
       return prom;
    });
    
    Promise.all(promiseArray).then(imagesLoaded);
    
    function imagesLoaded(){
       //start canvas work.
    
       //when needing to draw image, access the loaded image in loadedImages
       ctx.drawImage(loadedImages['imageurl.jpg'], 300, 100);
    }
    

提交回复
热议问题