ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 图像预加载器如何工作?

2019-09-17 13:32:57  阅读:169  来源: 互联网

标签:html preloading javascript image asynchronous


我很难理解图像预加载器在java脚本中的工作方式.因此,如果有人能够解释他们如何使用一个可以帮助很多的例子.
没有jquery

解决方法:

加载单个图像

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

// 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');

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

那么你怎么知道图像什么时候完全加载并准备好使用?

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

img.onload = theImageHasFinishedLoading;

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

完整的图像加载过程将按以下顺序进行:

// 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添加到此数组中.

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

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

// For example
var imgs=[];

>将新图像元素添加到图像对象数组(为URL数组中的每个URL添加一个新图像).

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

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

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

>使用图像URL数组将每个图像的.src设置为单个URL.

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

>在theImageHasFinishedLoading回调中,每次成功加载新图像时递增计数器.

// For example
var counter=0;

function theImageHasFinishedLoading(){
    counter++;
}

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

    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>

标签:html,preloading,javascript,image,asynchronous
来源: https://codeday.me/bug/20190917/1809429.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有