Run JavaScript When New Images are Loaded - javascript

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";
....

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 !

JavaScript image array in NetBeans

I am a very new coder and even newer to Stack so please help me out if my question is bad or not understandable!
I have been following a number of tutorials on this site and others on creating a JavaScript slideshow gallery for a website project I am making for school. I have the html written up, the first image will appear as it is loaded through html, but the debug console keeps saying that it is receiving empty responses when I try to run the webpage through the Chrome Connector. All that appears on the site is an empty image holder.
I reckon it's either something to do with NetBeans and my file structure within the project that it can't find the files or my code, but I've tried every method I've seen to load the images to the array. I even wiped and loaded a whole new set of images! No joy. I just can't figure out what is going on, every tutorial makes it look so easy! My file tree in netbeans is basic and the HTML and css files find the images no problem! I tried loading a screenshot of the file tree but i'm not allowed. Basically my photos are in a folder called images in the Site Root folder.
var bigPictureArray = [];
bigPictureArray[0]= new Image();
bigPictureArray[0].src='images/cup1.jpe)';
bigPictureArray[1]= new Image();
bigPictureArray[1].src='images/cf1.jpeg';
bigPictureArray[2]= new Image();
bigPictureArray[2].src='images/cf2.JPG';
bigPictureArray[3]= new Image();
bigPictureArray[3].src='images/cf3.jpg';
bigPictureArray[4]= new Image();
bigPictureArray[4].src='images/cf4.jpeg';
bigPictureArray[5]= new Image();
bigPictureArray[5].src='images/cf5.jpeg';
bigPictureArray[6]= new Image();
bigPictureArray[6].src='images/cf6.jpeg';
bigPictureArray[7]= new Image();
bigPictureArray[7].src='images/cf7.jpeg';
bigPictureArray[8]= new Image();
bigPictureArray[8].src='images/cf8.jpeg';
bigPictureArray[9]= new Image();
bigPictureArray[9].src='images/cf9.jpeg';
bigPictureArray[10]= new Image();
bigPictureArray[10].src='images/cf10.jpeg';
//function to display image slideshow
// found on youtube # https://www.youtube.com/watch?v=-MifpF7p1P0
var bpa_k = 0;
var bpa_elem;
function bpaNext(){
bpa_k++;
bpa_elem.style.opacity = 0;
if(bpa_k > (bigPictureArray.length -1)){
bpa_k = 0;
}
setTimeout("bpaSlide()", 1500);
}
function bpaSlide(){
bpa_elem.innerHTML=bigPictureArray[bpa_k];
bpa_elem.style.opacity = 1;
setTimeout("bpaNext()", 2000);
}
////the tutorial i used added this to the html files to load the slideshow in script tags
<img src="cup1.jpe" id="bpa" alt="slideshow">
<script>
bpa_elem = document.getElementById("bpa");
bpaSlide();
</script>
again sorry if my question is a mess or the problem is ridiculous. I've been looking at this so long I am almost blind to it! I'm probably missing a really basic thing!

How to add event listener to not-yet existing elements (without jQuery)?

Here is the scenario I simplified:
I am trying to access an image link in, say, page "A". So my script opens page "A". But it's not that simple. Due to various reasons (i.e. login credentials, redirection), I cannot just use
window.open(url).getElement...
because what I get here does not contain the target image I want.
One way I could (which I did) do this is by setting
window.open(url).onload=function(){//get the image};
that is, I can get the image when the page is fully loaded (thus including the redirection).
My question then is, is there a way to have something that accomplisheselement.onload when the element has NOT yet existed? In this scenario, it would be to get the image URL without waiting for the image to load completely.
The image object is good for this.
Just put this function where you'd like to load an image.
function loadImageInto(id){
var image = new Image();
image.onload = function(){
document.getElementById(id).src = image.src;
};
image.src = "imagefile.jpg";
}
If you want an event handler you can do this.
function loadImageInto(id){
return function(){
var element = this;
if(typeof id !== 'undefined'){
element = document.getElementById(id);
}
var image = new Image();
image.onload = function(){
element.src = image.src;
};
image.src = "imagefile.jpg";
}
}
This of course will only work if you know the image url ahead of time.

Loading an image with external js file

I'm trying to load an image using an external js file that contains the following:
myimage = new Image(1,1);
myimage.src = 'http://myserver.com/pixel.gif';
I see the js file loaded and no error in the console, but also no call to my image pixel. Any idea?
EDIT:
After the first responses I tried the following and it still doesn't work:
var myimage = document.createElement("img");
myimage.src = 'http://myserver.com/pixel.gif';
myimage.height = "1";
myimage.width = "1";
document.body.appendChild(myimage);
The image needs to be inserted into the page/DOM.
The image will not be called until it is placed into the page/DOM directly, and therefore loaded.
What you want will happen with something like: document.body.appendChild(myimage)
There is an example of how to do this at http://www.w3schools.com/tags/canvas_drawimage.asp by inserting the image into a canvas.
A small modification which I found makes this work better is putting the drawImage line into an img.onload callback like this:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
img.onload(function() {ctx.drawImage(img,10,10);});

Why do my canvases only load on refresh?

I have a web page which contains an iframe, the iframe contains a table which contains up to 1,000 canvas elements. The canvas elements are filled by a function defined in the iframe, which is called by the parent page. The function iterates and fills each canvas with a base64 data URI contained in a hidden span in the parent page. I have read a few other Stackoverflow posts regarding similar issues but I have already tried the most commonly used suggestion (using onload) and that does not seem to work. I am fairly fresh to html/javascript so I doubt I am doing things the best way. I was hoping someone could guide me on how to assure that all the canvas elements are successfully filled with the base64 data on the first load so I don't need to refresh multiple times to get me thumbnails? Here is some code, it is VERY trimmed up code from my html page. If I were to paste the entire page, it might be a bit too much too handle sensibly. Here is what I believe to be the essential actors.
My onload call to my function which fills the canvases, this is on the main page which contains the iframe -
<body onload="document.getElementById('framePage').contentWindow.fillCans();">
Here is the fillCans() function which is contained within the framePage iframe (I probably should move this to the main html page, but so far this is how the script has... evolved haha). pgCnt element contains the "counter" numbers if you will. It will defines how many elements to iterate through. When var c is assigned, the "can"+i elements are the canvases. When var imgSrc is assigned, the "span"+i elements are the hidden span elements on the parent page which contain the base 64 data URIs -
function fillCans() {
var cnt = document.getElementById("pgCnt").innerHTML;
var cnt = cnt.split("-");
var cnt1 = cnt[0];
var cnt2 = cnt[1];
for (var i=cnt1; i <= cnt2; i++) {
var targ = "span"+i
var c = document.getElementById("can"+i);
var ctx = c.getContext("2d");
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0,0,128,128);
var image = new Image();
var imgSrc = parent.document.getElementById("span"+i).innerHTML;
imgSrc = imgSrc.split("*");
image.src = imgSrc[0];
ctx.drawImage(image,0,0);
}
Like I said, this will load fine, firebug reports no errors, however all the canvases are white with no thumbnails. When I hit refresh a few times they all finally load. I've read that the image data is asynchronously loaded but I am not certain to as what that means, I assume it means it doesn't play by the rules that onload plays by? Anyways as usual, thanks for all the help stackoverflow community. It will be great to know how to get these thumbnails to load successfully on the first page load.
After #Sebastian's great suggestions I was able to get my JavaScript functioning as it should. I am pasting in the new function. As it works now, in case anyone ever comes across a similar issue. I had to implement an onload call to a function which drew the image, and then utilize in IIFE for loop to insure that each thumbnail was drawn with correctly iterated data.
function fillCans() {
var cnt = document.getElementById("pgCnt").innerHTML;
var cnt = cnt.split("-");
var cnt1 = cnt[0];
var cnt2 = cnt[1];
for (var i=cnt1; i <= cnt2; i++) {
(function(iterable){
var c = document.getElementById("can"+iterable);
var ctx = c.getContext("2d");
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0,0,128,128);
var image = new Image();
var imgSrc = parent.document.getElementById("span"+iterable).innerHTML;
imgSrc = imgSrc.split("*");
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = imgSrc[0];
})(i);
}
}
You are right, the problem is that the image has to be loaded first, before you can draw it.
In your case image is not loaded at the time you call
ctx.drawImage(image,0,0);
However later on the browser has cached the image URL and in between the calls to the assignment of the source property and the drawImage call the browser has already retrieved the image from the cache.
To make it work in any case, you need to wait for the image to load:
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = imgSrc[0];
Be sure to first register the callback and then set the src.
See HTML Canvas DrawImage Tutorial

Categories

Resources