Как работают предварительные загрузчики изображений?
Мне трудно разобраться, как работают предварительные загрузчики изображений в java-скрипте. Так что, если бы кто-то мог объяснить, как они работают, на примере, который очень помог бы.нет JQuery
1 ответ
Загрузка одного изображения
Браузер будет загружать изображения асинхронно... то есть, когда браузер получает .src
изображения, оно начнет загружать это изображение в фоновом режиме, но также продолжит обработку кода JavaScript сразу после .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');
Предупреждение будет отображаться еще до того, как изображение будет полностью загружено и готово к использованию.
Так как же узнать, когда изображение полностью загружено и готово к использованию?
Ответ: Вы можете сказать браузеру "перезвонить", когда он закончит загрузку изображения. Вы получаете "обратный вызов", добавляя функцию "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=[];
добавлять
new Image
элементы в массив изображения объекта (добавить одинnew Image
для каждого 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>