JavaScript image loading in percents - javascript

Is there any way to show "percentage-load-bar" while loading an image in js?
In other words I want to use this:
var img = new Image();
img.onload = function() {
document.querySelector('#percents').innerHTML = 'all done';
};
img.onreadystatechange = function(e) {
document.querySelector('#percents').innerHTML = e.percentsLoaded;
};
img.src = 'http://example.com/image.png';

Javascript has no intermediate events for loading resources. You can however show a loading bar if you are loading more than one image but I'm guessing that's not the case.
If you do really want this I think the only solution is to use Flash, which can do a number of fancy things but .. well .. it's Flash :/
Look at some of the big album-image hosting sites and see if they have a solution.

Related

onload or addEventListener on new Image() canvas doesn't work

I have a problem when I load local (or online) images. So I use canvas HTML 5 then I put a new image on it but image never load at first time. I need to refresh page one time. The first time, images are loaded but not in good time so there are not showed. Then,, when I refresh, images are still in caches of my browser (firefox 50) so that's work.
I saw on forum that I need to wait with :
myimage.onload = function(){
context.drawImage(myimage,0,0,myimage_size,myimage_size);
}
myimage.src = mysrc;
But this doesn't work, images are not showed. So I try another way with that:
var elementHTML = document.createElement('img');
var canvas = document.createElement('canvas');
canvas.width = my_size;
canvas.height = my_size;
elementHTML.appendChild(canvas);
context = canvas.getContext('2d');
base_image = new Image();
base_image.src = base_image_src;
base_image.addEventListener('load', test(this.owner));
function test(owner){
//here there is the trick, with that, all work but I need program work without that !
while(window.alert("done")){};
context.drawImage(base_image,0,0,my_size,my_size)
if (owner == "1") {
//I modified some colors of my image
recolorRGBImage(context,lineTuleColorRGB,playerLineTuleColorRGB_1,lineTrigger);
recolorRGBImage(context,fillTuleColorRGB,playerFillTuleColorRGB_1,fillTrigger);
}
else {
recolorRGBImage(context,lineTuleColorRGB,playerLineTuleColorRGB_2,lineTrigger);
recolorRGBImage(context,fillTuleColorRGB,playerFillTuleColorRGB_2,fillTrigger);
}
}
That's work but obviously, alerts must never show. How can I do what I did without alert? (Alert used like onload because these methods doesn't work)
Thanks !

get image size (kb) with javascript with out loading it

Is there any way to get image size (kb) before loading it in browser by java script ?
for example there is an image in this address : "mysite.com/content/sample.jpg"
now how can we understand how much is the size (kb) of this image?
You can get it like below
window.onload = function() {
var image = new Image();
image.onload = function() {
var info = "Image Info:<br>Width: "+this.width+", Height: "+this.height;
document.getElementById("imageInfo").innerHTML = info;
}
image.src = 'http://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg';
}
Here is the sample - http://plnkr.co/edit/X1cqZYv93FzK4zC5kRE7?p=preview
If it's only ever a jpeg, you can just load the first chunk of the file which contains the EXIF metadata. That metadata contains width and height most of the time, although you can't be 100% certain that it's there or that it's correct. But it's probably your best bet. There are a couple of nice EXIF libraries in Javascript, and I've used this one: https://github.com/bwindels/exif-parser
It still requires you to make an HTTP request for it though, so if that's what you're worried about, there's no way to avoid it.

Run JavaScript When New Images are Loaded

I did some research about this problem, but my situation is strange. I wrote a function to use ajax to get some image resource and stored it in a variable in js. window.onload() is working fine at the first time, which load all image to variable before displaying, but after that I clicked a link to load more pictures to that variable using ajax again, I do not know how to display those new ones ONLY when they are fully stored in that variable. Please help me with that.
Thanks, Dai.
The loading of individual images can be tracked with img.onload. So, if you're loading a bunch of images and want to know when they are all loaded, you have to put onload handlers on all of them and accumulate a count for when they are all loaded.
var loadCnt = 0;
function cntLoads() {
++loadCnt;
if (loadCnt > 20) {
// all images loaded now, do whatever you want to do here
}
}
var img1 = new Image();
img1.onload = cntLoads;
img1.src "xxxx";
var img2 = new Image();
img2.onload = cntLoads;
img2.src "yyyyy";
....

Onload issue for Progress bar for preloaded images

I would like to try and set up a progress bar for several images while their loading and haven't been able to get it to work. I have several images that are preloaded like:
var Image1 = new Image();
var Image2 = new Image();
var Image3 = new Image();
Image1.onload = moveProgressBar();
Image2.onload = moveProgressBar();
Image3.onload = moveProgressBar();
Image1.src = url;
Image2.src = url;
Image3.src = url;
Something weird is happening since they're immediately running the moveProgressBar() function even though the images aren't entirely loaded yet. This happens even when approaching the page with no cache and with cache. Am I missing something? Any help would be appreciated.
The js onload event on images is a big messy mess. Different browsers handle it differently, and different versions (mostly IE) handle it differently. Plus, most browsers have iffy bugs.
Here is a short checklist:
set your onload BEFORE you set your src. (Wait for it, it will get quirkier...)
Handle onerror as well.
Handle images that already was cached. Sometimes they will not fire onload, while other times they will fire and do so imediately.
Use a generic belt-and-suspenders setTimeout()-function that polls to see if the image has gotten a width or height in the DOM. This is done differently in different browsers/versions, which means you'll have to use feature detection, starting with naturalWidth, then move on to getAttribute(width) before image.width.
And then you will still probably have some bugs... but you will only know if you test all browser/versions you intend to support.
For reference, the error was that Noah was calling each function and assigning the result to the onload. It should have been:
Image1.onload = moveProgressBar; // note the lack of ()

Load and display multiple animated gifs at the same time (synchronised) with Javascript

I'm by no means any kind of coder or programmer, but I've been trying to load and display some gifs so that they all animate from the beginning at the same time. In other words, I need them to be synchronised.
I've done a lot of Googling and what I've come up with seems to work with Chrome/Safari and Firefox, but as usual, Internet Explorer refuses to cooperate.
My current code is this:
var images = ["thephoto1", "thephoto2", "thephoto3", "thephoto4", "thephoto5"];
function initImages() {
for (var i = 0; i < images.length; i++) {
imageId = images[i];
image = document.getElementById(imageId);
image.style.visibility = "visible";
}
}
function preloadImages(urls) {
var img = new Array();
for (var i = 0; i < urls.length; i++) {
img[img.length] = new Image();
img[img.length - 1].src = urls[i];
}
}
window.onload = function() {
var img = new Array(
"http://desmond.imageshack.us/Himg391/scaled.php?server=391&filename=countdown.gif&res=medium",
"http://icanhascheezburger.files.wordpress.com/2010/11/funny-pictures-gif-cat-love.gif",
"http://i52.photobucket.com/albums/g9/cpchick/Random%20Gifs/therock.gif",
"http://www.mobileapples.com/Assets/Content/Screensavers/dc_1owy86mw.gif",
"http://www.pptbackgrounds.fsnet.co.uk/images/powerpoint-countdown-u1.GIF"
);
preloadImages(img);
initImages();
}
With some added CSS:
.preload
{
visibility: hidden;
}
It's basically this and this script combined.
You can view a live example here: http://jsfiddle.net/AN9uB/
Some possible methods or potentially helpful posts:
Restart an animated GIF from JavaScript without reloading the image.
Javascript to only display animated gif when loaded.
However from reading the comments on those links, I'm not entirely sure they're possible.
The test gifs I'm using are just random images I found and a small forewarning, some of the images are fairly large since I needed to test a variety gifs ranging in size and duration. All of the gifs loop except for the first countdown image which only plays once.
On some occasions the first countdown image doesn't play at all (it's stuck on 10) when viewing the page with Firefox 3.6.18, but otherwise the rest of the gifs all load and display at the same time.
The main problem is that I cannot think of a way to make this work with Internet Explorer. I thought perhaps to preload the images and then refresh the page via javascript. It's an ugly solution, but I think it would work.
Flash is the obvious tool to be doing this kind of thing in, but the friend who I'm making this for only uses gifs.
Is there a more elegant solution that works across all major browsers? Also ideally, to only use Javascript, not JQuery.
Thanks for any help.
Well, you're not really preloading the images, because you're only calling the preloadImages function after the pages has loaded, i.e. after the actual IMG tags in the html have been read, and the browser's probably started downloading them. The last part may depend on the visibility:hidden style, but I'm not sure - at least I don't expect all browsers to agree on what to do in that case.
Also, you have the URLs defined both in the JavaScript, and in the HTML. That's both redundant and also harder to change later.
I must admit I have no idea if this will work right everywhere, but you might try
only having the image URLs in JavaScript - you can then add then
into the HTML, when they're ready
using the onload event handler
on the JS Image objects to assert that an image has been loaded.
Once they've all loaded, add them to the document (i.e. the page).
Now, I don't know when a given browser starts the animation-clock on a gif. If it starts the moment the gif has been loaded, there's not much you can do, since the gif's won't load at the same time. If, however, they first start animating when they're placed in the document (which seems probable, but never trust a browser), then there's a chance.
// This function will add an array of images to div#images
function showImages(images) {
var container = document.getElementById("images"); // get the #images div
for( var i = 0, l = images.length ; i < l ; i++ ) {
var img = document.createElement('IMG'); // create the IMG tag
img.src = images[i].src; // set the src - the image should be preloaded when this happens
container.appendChild(img); // add the IMG tag to the #images div
}
}
// This one will create JS Image objects from an array of URLs
function loadImages(urls) {
var remaining = urls.length; // the images still waiting to be fetched
var images = []; // empty array to hold the created Image objects
// this function will be called for Image object that is loaded
var onloadHandler = function() {
remaining--; // decrement the number of remaining images
if( remaining < 1 ) {
showImages(images); // if all images have loaded, add them to the page
}
};
// create an Image object for each URL
for( var i = 0, l = urls.length ; i < l ; i++ ) {
var img = new Image();
img.onload = onloadHandler; // set the onload-handler before setting the src
img.src = urls[i];
images.push(img); // add the Image object to the images array
}
}
window.onload = function() {
var urls = [
"http://desmond.imageshack.us/Himg391/scaled.php?server=391&filename=countdown.gif&res=medium",
"http://icanhascheezburger.files.wordpress.com/2010/11/funny-pictures-gif-cat-love.gif",
"http://i52.photobucket.com/albums/g9/cpchick/Random%20Gifs/therock.gif",
"http://www.mobileapples.com/Assets/Content/Screensavers/dc_1owy86mw.gif",
"http://www.pptbackgrounds.fsnet.co.uk/images/powerpoint-countdown-u1.GIF"
];
loadImages(urls);
};
Here's a jsfiddle of it all: http://jsfiddle.net/Frqys/2/
Again, I have no idea if this'll actually work in every browser. It seems ok in Safari, Chrome and Firefox (all on Mac OS), but it's impossible to be sure. I'd advise you to copy a gif file a number of times, and give each file a different name, so it'll have a unique URL. That should prevent it from caching, and keep its animation clock separate. Then try loading all those GIFs instead of a bunch of different ones, and see if they stay in sync.

Categories

Resources