图像预加载器如何工作? [英] How do image preloaders work?

查看:27
本文介绍了图像预加载器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解图像预加载器在 Java 脚本中的工作原理.因此,如果有人可以通过一个示例来解释他们如何工作,那将会有很大帮助.没有jquery

I have a hard time getting my head around how image preloaders work in java-script. So if someone could could explain how they work with an example that would help a lot. no jquery

推荐答案

加载单个图像

浏览器将异步加载图像...意味着当浏览器获得图像的 .src 时,它将开始在后台加载该图像,但也会继续处理 javascript 代码直接在 .src

The browser will load images asynchronously...meaning when the browser is given the .src of an image, it will start loading that image in the background, but will also continue processing the javascript code directly after .src

// create a new image object
var img=new Image();

// set the image object's image source
img.src='myImage.png';

// do some stuff while the image is loading in the background
alert('Your image has started loading, but is not yet complete');

即使在图像完全加载并准备好使用之前,警报也会显示.

The alert will display even before the image is fully loaded and ready to use.

那么您如何知道图像何时完全加载并可以使用?

So how do you know when the image is fully loaded and ready to use?

答案:您可以告诉浏览器在完成加载图像后给您回电".您可以通过在图像对象上添加img.onload"函数来回调".每当浏览器加载完图片时,浏览器都会触发img.onload"函数中的代码.

Answer: You can tell the browser to "call you back" when it finishes loading the image. You get "called back" by adding an "img.onload" function on the image object. Whenever the browser finishes loading the image, the browser will trigger the code in the "img.onload" function.

img.onload = theImageHasFinishedLoading;

function theImageHasFinishedLoad(){
    alert('Your image has finished loading...you can use it now');
}

完整的图片加载过程会按照这个顺序发生:

The complete image loading process will occur in this sequence:

// happens 1st
var img=new Image();

// happens 2nd: this callback is ASSIGNED, but NOT TRIGGERED yet
//     until the image has fully loaded
img.onload = theImageHasFinishedLoading;

// happens 3rd
img.src='myImage.png';

// happens 4th
alert('Your image has started loading, but is not yet complete');

// happens 5th after the browser has fully loaded the image
//     (The browser will call this function automatically because .onload was set)
function theImageHasFinishedLoad(){
    alert('Your image has finished loading...you can use it now');
}

预加载多张图片

要预加载多个图像:

  • 创建一个数组来保存您的所有图片 URL,并将您的图片 URL 添加到该数组中.

  • Create an array to hold all your image URLs and add your image URLs to this array.

// For example
var imageURLs=[];
imageURLs[0]='myImage.png';

  • 创建一个数组来保存所有图像对象(==您的实际图像).

  • Create an array to hold all your image objects (==your actual images).

    // For example
    var imgs=[];
    

  • new Image 元素添加到图像对象数组(为 URL 数组中的每个 URL 添加一个 new Image).

  • Add new Image elements to the image object array (add one new Image for each URL in the URL array).

    //For example
    imgs[0] = new Image();
    

  • 将每个图像对象的 .onload 回调设置为相同的函数.

  • Set every image object's .onload callback to the same function.

    // For example
    imgs[0].onload = theImageHasFinishedLoading;
    

  • 使用图片网址数组将每张图片的.src设置为单独的网址.

    // For example
    imgs[0].src = imageURLs[0];
    

  • theImageHasFinishedLoading 回调中,每次成功加载新图像时都会增加一个计数器.

  • In the theImageHasFinishedLoading callback, increment a counter every time a new image is successfully loaded.

    // For example
    var counter=0;
    
    function theImageHasFinishedLoading(){
        counter++;
    }
    

  • 当计数器达到与图像 URL 数组相同的长度时,您就会知道所有图像都已完全加载.

    You will know that all images are fully loaded when the counter reaches the same length as your image URL array.

        function theImageHasFinishedLoading(){
            counter++;
            if(counter>=imageURLs.length){
                alert('All the images have successfully preloaded. Go use them now!');
            }
        } 
    

    这是完整的示例代码和演示:

    window.onload=(function(){
    
    
      // canvas related variables
      var canvas=document.getElementById("canvas");
      var ctx=canvas.getContext("2d");
      var cw=canvas.width;
      var ch=canvas.height;
    
      // put the paths to your images in imageURLs[]
      var imageURLs=[];  
      imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face1.png");
      imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face2.png");
    
      // the loaded images will be placed in imgs[]
      var imgs=[];
      var imagesOK=0;
      startLoadingAllImages(imagesAreNowLoaded);
    
      // Create a new Image() for each item in imageURLs[]
      // When all images are loaded, run the callback (==imagesAreNowLoaded)
      function startLoadingAllImages(callback){
    
        // iterate through the imageURLs array and create new images for each
        for (var i=0; i<imageURLs.length; i++) {
          // create a new image an push it into the imgs[] array
          var img = new Image();
          // Important! By pushing (saving) this img into imgs[],
          //     we make sure the img variable is free to
          //     take on the next value in the loop.
          imgs.push(img);
          // when this image loads, call this img.onload
          img.onload = function(){ 
            // this img loaded, increment the image counter
            imagesOK++; 
            // if we've loaded all images, call the callback
            if (imagesOK>=imageURLs.length ) {
              callback();
            }
          };
          // notify if there's an error
          img.onerror=function(){alert("image load failed");} 
          // set img properties
          img.src = imageURLs[i];
        }      
      }
    
      // All the images are now loaded
      // Do drawImage & fillText
      function imagesAreNowLoaded(){
    
        // the imgs[] array now holds fully loaded images
        // the imgs[] are in the same order as imageURLs[]
    
        ctx.font="30px sans-serif";
        ctx.fillStyle="#333333";
    
        // drawImage the first image (face1.png) from imgs[0]
        // and fillText its label below the image
        ctx.drawImage(imgs[0],0,10);
        ctx.fillText("face1.png", 0, 135);
    
        // drawImage the first image (face2.png) from imgs[1]
        // and fillText its label below the image
        ctx.drawImage(imgs[1],200,10);
        ctx.fillText("face2.png", 210, 135);
    
      }
    
    
    
    }); // end window.onload

    body{ background-color: ivory; }
    #canvas{border:1px solid red;}

    <canvas id="canvas" width=400 height=200></canvas>

    这篇关于图像预加载器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆