Comment fonctionnent les préchargeurs d'images?

J'ai du mal à comprendre comment fonctionnent les précharges d'image dans java-script. Donc, si quelqu'un pouvait expliquer comment ils fonctionnent avec un exemple qui aiderait beaucoup. Pas de jquery

Chargement d'une seule image

Le navigateur va charger des images de manière asynchrone … signifie que lorsque le navigateur reçoit le .src d'une image, il va commencer à charger cette image en arrière-plan, mais continuera également à traiter le code javascript directement après .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'); 

L'alerte s'affiche avant même que l'image soit complètement chargée et prête à l'emploi.

Alors, comment savez-vous quand l'image est complètement chargée et prête à l'emploi?

Réponse: Vous pouvez indiquer au navigateur de «vous rappeler» lorsqu'il finit de charger l'image. Vous obtenez "rappel" en ajoutant une fonction "img.onload" sur l'objet image. Chaque fois que le navigateur finit de charger l'image, le navigateur déclenchera le code dans la fonction "img.onload".

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

Le processus complet de chargement d'image se produira dans cette séquence:

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

Pré-chargement de plusieurs images

Pour précharger plusieurs images:

  • Créez un tableau pour contenir toutes vos URL d'image et ajoutez vos URL d'image à ce tableau.

     // For example var imageURLs=[]; imageURLs[0]='myImage.png'; 
  • Créez un tableau pour contenir tous vos objets d'image (== vos images réelles).

     // For example var imgs=[]; 
  • Ajouter de new Image éléments d'image au tableau d'objets d'image (ajouter une new Image pour chaque URL dans le tableau d'URL).

     //For example imgs[0] = new Image(); 
  • Configurez le rappel de chaque objet d' .onload sur la même fonction.

     // For example imgs[0].onload = theImageHasFinishedLoading; 
  • Utilisez le tableau d'URL de l'image pour définir le .src de chaque image sur l'URL individuelle.

     // For example imgs[0].src = imageURLs[0]; 
  • Dans le rappel de l'image, theImageHasFinishedLoading un compteur chaque fois qu'une nouvelle image est chargée avec succès.

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

Vous savez que toutes les images sont entièrement chargées lorsque le compteur atteint la même longueur que le tableau d'URL de votre image.

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

Voici un code d'exemple complet et une démonstration:

 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>