Checking for multiple images loaded - javascript

I'm using the canvas feature of html5. I've got some images to draw on the canvas and I need to check that they have all loaded before I can use them.
I have declared them inside an array, I need a way of checking if they have all loaded at the same time but I am not sure how to do this.
Here is my code:
var color = new Array();
color[0] = new Image();
color[0].src = "green.png";
color[1] = new Image();
color[1].src = "blue.png";
Currently to check if the images have loaded, I would have to do it one by one like so:
color[0].onload = function(){
//code here
}
color[1].onload = function(){
//code here
}
If I had a lot more images, Which I will later in in development, This would be a really inefficient way of checking them all.
How would I check them all at the same time?

If you want to call a function when all the images are loaded, You can try following, it worked for me
var imageCount = images.length;
var imagesLoaded = 0;
for(var i=0; i<imageCount; i++){
images[i].onload = function(){
imagesLoaded++;
if(imagesLoaded == imageCount){
allLoaded();
}
}
}
function allLoaded(){
drawImages();
}

Can't you simply use a loop and assign the same function to all onloads?
var myImages = ["green.png", "blue.png"];
(function() {
var imageCount = myImages.length;
var loadedCount = 0, errorCount = 0;
var checkAllLoaded = function() {
if (loadedCount + errorCount == imageCount ) {
// do what you need to do.
}
};
var onload = function() {
loadedCount++;
checkAllLoaded();
}, onerror = function() {
errorCount++;
checkAllLoaded();
};
for (var i = 0; i < imageCount; i++) {
var img = new Image();
img.onload = onload;
img.onerror = onerror;
img.src = myImages[i];
}
})();

Use the window.onload which fires when all images/frames and external resources are loaded:
window.onload = function(){
// your code here........
};
So, you can safely put your image-related code in window.onload because by the time all images have already loaded.
More information here.

A hackish way to do it is add the JS command in another file and place it in the footer. This way it loads last.
However, using jQuery(document).ready also works better than the native window.onload.
You are using Chrome aren't you?

The solution with Promise would be:
const images = [new Image(), new Image()]
for (const image of images) {
image.src = 'https://picsum.photos/200'
}
function imageIsLoaded(image) {
return new Promise(resolve => {
image.onload = () => resolve()
image.onerror = () => resolve()
})
}
Promise.all(images.map(imageIsLoaded)).then(() => {
alert('All images are loaded')
})

Just onload method in for loop does not solve this task, since onload method is executing asynchronously in the loop. So that larger images in the middle of a loop may be skipped in case if you have some sort of callback just for the last image in the loop.
You can use Async Await to chain the loop to track image loading synchronously.
function loadEachImage(value) {
return new Promise((resolve) => {
var thumb_img = new Image();
thumb_img.src = value;
thumb_img.onload = function () {
console.log(value);
resolve(value); // Can be image width or height values here
}
});
}
function loadImages() {
let i;
let promises = [];
$('.article-thumb img').each(function(i) {
promises.push(loadEachImage( $(this).attr('src') ));
});
Promise.all(promises)
.then((results) => {
console.log("images loaded:", results); // As a `results` you can get values of all images and process it
})
.catch((e) => {
// Handle errors here
});
}
loadImages();
But the disadvantage of this method that it increases loading time since all images are loading synchronously.
Also you can use simple for loop and run callback after each iteration to update/process latest loaded image value. So that you do not have to wait when smaller images are loaded only after the largest.
var article_thumb_h = [];
var article_thumb_min_h = 0;
$('.article-thumb img').each(function(i) {
var thumb_img = new Image();
thumb_img.src = $(this).attr('src');
thumb_img.onload = function () {
article_thumb_h.push( this.height ); // Push height of image whatever is loaded
article_thumb_min_h = Math.min.apply(null, article_thumb_h); // Get min height from array
$('.article-thumb img').height( article_thumb_min_h ); // Update height for all images asynchronously
}
});
Or just use this approach to make a callback after all images are loaded.
It all depends on what you want to do. Hope it will help to somebody.

try this code:
<div class="image-wrap" data-id="2">
<img src="https://www.hd-wallpapersdownload.com/script/bulk-upload/desktop-free-peacock-feather-images-dowload.jpg" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-2" style="font-size:24px"></i>
</div>
<div class="image-wrap" data-id="3">
<img src="http://diagramcenter.org/wp-content/uploads/2016/03/image.png" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-3" style="font-size:24px"></i>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
var allImages = jQuery(".img-load").length;
jQuery(".img-load").each(function(){
var image = jQuery(this);
jQuery('<img />').attr('src', image.attr('src')).one("load",function(){
var dataid = image.parent().attr('data-id');
console.log(dataid);
console.log('load');
});
});
});
</script>

Related

Defer image and replacement loaded

I have a JS function that once the page is loaded swaps the assets from a transparent gif to full images via the data-src below.
<img src="1x1.gif" data-src="full-photo.png" class="asset" /> // My image
window.addEventListener('load', function() {
defer_images();
function defer_images() {
var loadedImages = 0;
var imgDefer = document.getElementsByClassName('asset');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
var iWidth = imgDefer[i].naturalWidth; // Check image exists
if (iWidth) {
loadedImages++;
} else {
console.log("Image missing: "+imgDefer[i].getAttribute('data-src'));
}
}
// all images exist and have been replaced
if (imgDefer.length === loadedImages) {
doThings();
}
}
}
});
This seems to work fine on a cached page. But if I reload the page and switch tabs – the code doesn't complete as loadedImages++ is never fired.
I can't use setInterval or setTimeout to re-check as this code is used in DoubleClick.
Any help would be really appreciated.
You can detect that images are loaded by using the onload event and failed to load using onerror.
for (var i = 0; i < imgDefer.length; i++) {
var img = imgDefer[i];
if (img.getAttribute('data-src')) {
img.addEventListener("load", function() {
loadedImages++;
});
img.addEventListener("error", function() {
console.log("Image missing: "+ this.getAttribute("data-src"))
});
img.src = img.getAttribute('data-src');
}
}
The reason it fails for non-cached is because it takes time to load the image, and your for loop is fast. Use the events to trigger when the image is loaded.
You can read more here.
Note: Detecting that all images are loaded may require using promises:
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener("load", () => resolve(img));
img.addEventListener("error", err => reject(err));
img.src = src;
// append to the dom or replace here
});
};
Then you can use then() and catch()

Add previous and next functions for slideshow with window.onload JavaScript

I want to create a JavaScript program who allow the user to switch between
image by using previous and next button. But i can't use window.onload to load the next image cause window.onload overwrite the previous window.onload. I want to know if their exist any solution to make window.onload work with two functions in the same time. If window.onload can't be usable for this kind of program you can suggest me another solution.
Thank you.
var i =0;
var image = [];
image[0]= 'image.jpg';
image[1]= 'image2.jpg';
image[2]= 'panther.jpg'
function next(){
document.slide.src = image[i];
if(i<image.length-1){
i++;
}
else{
i=0;
}
document.getElementById('bouton1').addEventListener('click',next);
}
function previous(){
document.slide.src = image[i];
if(i>0){
i--;
}
else{
i=image.length-1;
}
document.getElementById('bouton2').addEventListener('click',previous);
}
window.onload = next;
window.onload = previous;
Needed a couple of changes, can you test it like this. Note we changed the onload to attach listeners. See comment.
var i =0;
var image = [];
image[0]= 'image.jpg';
image[1]= 'image2.jpg';
image[2]= 'panther.jpg'
function next(){
document.slide.src = image[i];
if(i<image.length-1){
i++;
}
else{
i=0;
}
}
function previous(){
document.slide.src = image[i];
if(i>0){
i--;
}
else{
i=image.length-1;
}
}
// This is window.onload
(function(){
// Move calls to attach event listeners here
document.getElementById('bouton2').addEventListener('click',previous);
document.getElementById('bouton1').addEventListener('click',next);
})();
addEventListener is a better method for adding an event handler without replacing an existing one.
window.addEventListener('load', e => { /* ... */ });
As a rule of thumb, any on(blah) attributes in the DOM can be replaced with addEventListener(blah, ...).
I'm not exactly sure about your idea behind window.onload, if you want to preload images (so the user does not have to wait for the image to load on buttons click...) than you could use new Image() and something like:
const EL_slide = document.getElementById("slide");
const EL_prev = document.getElementById('prev');
const EL_next = document.getElementById('next');
const image = [
'//placehold.it/800x600/0bf?text=1',
'//placehold.it/800x600/f0b?text=2',
'//placehold.it/800x600/0fb?text=3'
];
const n = image.length;
let i = 0;
// Preload images
image.forEach(src => {
var img = new Image();
img.src = src;
});
// Animation logic
function anim() {
if((/prev|next/).test(this.id)) i = this.id === "next" ? ++i : --i;
i = i<0 ? n-1 : i%n; // Index fixer (prevents out of bound index)
EL_slide.style.backgroundImage = `url('${image[i]}')`
}
// Events
[EL_prev, EL_next].forEach(EL => EL.addEventListener('click', anim));
// Load first!
anim();
#slide {
height: 70vh;
transition: 0.3s;
background: none 50% 50% / cover no-repeat;
}
<button id="prev">←</button>
<button id="next">→</button>
<div id="slide"></div>
and just make sure to place your Javascript right before the closing </body> tag.

get uploaded image height and width on callback -javascript

I need to load multiple image asynchronously from file field and them check if the dimensions are valid or not. I am pretty close, I just need to get the height of previously loaded image on call back. This is my effort so far:
let files = this.fileUpload.files; //get all uploaded files
for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
console.log(f);
let img = new Image();
img.name=f.name;
img.size=f.size;
img.onload = () =>{alert(img.height)} //it is giving height here
if (img.complete) { //callback
alert(img.name + 'loaded');
load_count++;
library_store.uploaded_image.push(
{
height:img.height,
width:img.width, // not coming, just wondering how to get
//the image height from load
name:img.name,
size:img.size
}
);
}
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
What is the best way to do this?
Wouldn't you want to move library_store logic to img.onload? Like below:
let files = this.fileUpload.files; //get all uploaded files
for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
console.log(f);
let img = new Image();
img.name=f.name;
img.size=f.size;
img.onload = function() {
// hoping that ```this``` here refers to ```img```
alert(this.name + 'loaded');
load_count++;
library_store.uploaded_image.push({
height:this.height,
width:this.width,
name:this.name,
size:this.size
});
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
}
// img.onload = () =>{alert(img.height)} //it is giving height here
/*
if (img.complete) { //callback
alert(img.name + 'loaded');
load_count++;
library_store.uploaded_image.push({
height:img.height,
width:img.width,
name:img.name,
size:img.size
});
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
}
*/
}
First let's see why you will always fall in this if(img.complete) block even though your images have not been loaded yet:
The complete property of the HTMLImageElement only tells if its resource is being loaded at the time you get the property.
It will report true if the loading succeed, failed, and if the src has not been set.
var img = new Image();
console.log('no-src', img.complete);
img.onerror = function() {
console.log('in-error', img.complete);
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=="
};
img.onload = function() {
console.log('in-load', img.complete);
}
img.src = "/some/fake-path.png";
console.log('while loading', img.complete);
And, at the time you get it, you didn't set this src attribute yet, so it will report true even though your image has not yet loaded its resource.
So what you want is an image preloader:
function preloadImages(srcArray, mustAllSucceed) {
return Promise.all(srcArray.map(loadImage));
function loadImage(src) {
return new Promise((resolve, reject) => {
var img = new Image();
img.onload = success;
img.onerror = mustAllSucceed ? success : reject;
img.src = src;
function success() {
resolve(img)
};
});
}
}
preloadImages(['https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg', 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Gran_Mezquita_de_Isfah%C3%A1n%2C_Isfah%C3%A1n%2C_Ir%C3%A1n%2C_2016-09-20%2C_DD_34-36_HDR.jpg'])
.then(images => {
images.forEach(img => console.log(img.src, img.width, img.height));
}, true);

Cannot get file size after uploading using JavaScript

I need to validate one file field with required width,height and if file has not uploaded using JavaScript but its not happening like this. Here is my code:
<input type="file" name="copImage" id="copImage" class="form-control" value="" onchange="setBackgroundImage(event);">
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
};
console.log('size bg',backImageHeight,backImageWidth);
}
Here I could not get the file height and width. I also to check the if file has not uploaded.
Pu the log statement inside the onload function. This is because you are trying to access the variable outside its scope, else define those variables outside onload function
bg.onload = function() {
var bgLoaded = true,
backImageHeight = this.height,
backImageWidth = this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
DEMO
suppose i have one button and without selecting file if I am clicking
on the file alert should say to select the file.
Seems you cannot do that with onchange event handler because if file is not loaded. nothing has changed and so function wont fire. In that case you can create a variable & update its state on file upload. On clicking of the button check the variable state
var isFileLoaded = false;
function setBackgroundImage(fileValue) {
var url = URL.createObjectURL(fileValue.files[0]);
bg = new Image();
if (fileValue.value !== '') {
bg.src = url;
bg.onload = function() {
bgLoaded = true;
isFileLoaded = true;
backImageHeight = this.height;
backImageWidth = this.width;
console.log('size bg', backImageHeight, backImageWidth);
};
}
}
function buttonClick() {
if (isFileLoaded) {
} else {
alert('No file selected')
}
}
DEMO 2
Hello You just need to log your height and width inside bg.onload function.these are outside of the scope of variables.thats why you not getting the height and width like this
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
Everything is fine in your code, you need to include console.log() within bg.onload block only like this .
function setBackgroundImage(e)
{
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
function isFileSelected()
{
return document.getElementById('copImage').files.length > 0;
}
You can use isFileSelected() function to know whether file is selected or not .

Why is only the first mouse-over and mouse-out working?

I have loaded a set of images and applied .mouseout() and .mouseover() on them. The problem is that after the first .mouseover() event the image gets larger and after .mouseout() is fired the image is returned back to its previous size. After the first time, no .mouseover() event gets fired in Firefox, but in Chrome it works. The problem is that the Chrome z-index property does not put the mouseover image on top of other images. What is the reason for these problems and how can I solve them?
var images = ['http://www.rd.com/wp-content/uploads/sites/2/2016/04/01-cat-wants-to-tell-you-laptop.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://pershanpet.ir/wp-content/uploads/2016/05/144-jpravafcbn.jpg', 'http://www.animal-whisper.com/images/pic28.jpg'];
function loadImage(url) {
var promise = new Promise((resolve, reject) => {
var image = new Image();
image.onload = function() {
resolve(image);
};
image.onerror = function() {
var msg = "could not load image at url " + url;
reject(new Error(msg));
};
image.src = url;
image.style.width = '200px';
image.style.height = '200px';
});
return promise;
}
Promise.all(
images.map(function(elem) {
return loadImage(elem);
})
).then((img) => {
img.forEach(each => {
each.addEventListener('mouseover', function(event) {
this.style.zIndex = '2000';
this.style.transform = 'scale(1.5,1.5)';
});
each.addEventListener('mouseout', function(event) {
this.style.transform = 'scale(1,1)';
this.style.zIndex = '-1';
});
addImg(each);
});
});
function addImg(img) {
document.body.appendChild(img);
}
Maybe your images get under some other elements with z-index that is greater than -1. On mouseout try this.style.zIndex = '0'.
It appears that you're setting the image's z-index to -1. Any reason for that?
Try setting this.style.zIndex = '1'; on mouseout.

Categories

Resources