AddEventListener and image loader trouble - javascript

I had problem with event listener and image loader in my code. When i try to load and check status of loaded image based on event listener some of images skipped. I think browser can handle only one event and when active one isn't stopped next can work and skip its work. So few of images return wront status and can be used. Just give me some advices about this. Here is my code:
//Image loader
var urlList = [
'images/ground_02.png', // 0 - FG
'images/ground_layer0.png', // 1 - CITY
...
];
var urlListLength = urlList.length; //length of URL-array
var iCount = new Number(0); // Create zero-counter
var images = new Array(); // All images array. Each elem stores one image
var imageInfo = function(imageName, imageCount, imageWidth, imageHeight) { // Constructor for image data container
this.imageName = imageName; // Url of image
this.imageCount = imageCount; // Frames
this.imageWidth = imageWidth; // Width of images
this.imageHeight = imageHeight; // Height of images
};
var imageData = new Array(); // Images data array
for (var i=0; i!=urlListLength; ++i) { // Loop for each image load
images[i] = new Image(); // Image array.
images[i].addEventListener('load', function(i) {
imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height));
iCount++;
if (iCount == urlListLength) {
var loaded = true;
loop();
};
}, false);
images[i].src = urlList[i];
images[i].onerror=function() {
alert("FAIL "+this.src);
};
};

You have a problem at least here:
imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height));
load event is fired once image is loaded by browser. But it is not necessary that it will be fired in the same order as load is started. Basically, images[2] could be loaded before images[0] and images[1] and in that case iCount won't work.
You can use this instead of images[iCount] as in this case this will point to exact that image which has fired load event.
imageData.push(new imageInfo(this, this.width/this.height, this.width, this.height));
I think browser can handle only one event and when active one isn't
stopped next can work and skip its work.
Nope. That is wrong. Regularly all events will be fired. But JS is single threaded, so it will simply put an event into a queue and will run next event after previous is done. It will not skip any event.

This should work for all browsers, including IE6.
var list = [
'images/ground_02.png',
'images/ground_layer0.png'
],
images = {};
function loadImage() {
images[this.src] = {
loaded: (this.width > 0 ? true : false),
src: this.src,
width: this.width,
height: this.height
};
if (list.length < 1) return;
var url = list.pop(),
img = new Image();
img.onload = loadImage;
img.onerror = loadImage;
img.src = url;
}
loadImage(); // Initialize loading
And if you need to check if an image has been loaded:
function isImageLoaded(src) {
return (images[src] && images[src].loaded);
}
if (isImageLoaded('images/ground_02.png')) alert('Yes!');

Related

Javascript code executes correctly when debugging, but doesn't work without browser Dev Tools running

I am trying to build a simple image uploader/gallery viewer for a webpage using PhotoSwipe. The gallery viewer plugin works without issues and needs an array (items in the code below) with the image src and the width and height per image. The function readImageDimensions() gets the data and later saves it to items.
When I'm debugging the code it runs flawlessly and the gallery gets the data, but if I skip the debugger the item variable has indexed two objects, but the src, w, h all have null values. Is it something in the code that runs asynchronously or otherwise disrupt the flow when the code isn't running through the debug process?
Code for uploading and presenting the images:
var thumbsDiv = "";
var items = [];
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('.file-uploader').addEventListener('change', onFilesSelected, false);
thumbsDiv = document.querySelector(".thumbs-div");
}
function onFilesSelected(e) {
if (!e.target.files || !window.FileReader) return;
thumbsDiv.innerHTML = "";
var width = 0;
var height = 0;
items = [];
function readImageDimensions(data) {
var image = new Image();
image.src = data;
width = image.width;
height = image.height;
}
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function (f) {
if (!f.type.match("image.*")) {
return;
}
var reader = new FileReader();
reader.onloadend = function (e) {
var result = e.target.result;
var html = '<div class="img-wrap"><span class="close">×</span><img src="' + result + '"/>' + f.name + '</div>';
thumbsDiv.innerHTML += html;
readImageDimensions(result);
items.push({
src: result,
w: width,
h: height
});
}
reader.readAsDataURL(f);
});
}
Code for instantiating the gallery:
var openGallery = function () {
var pswpElement = document.querySelectorAll(".pswp")[0];
var options = {
index: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
}
The issue was in fact that the image data was loaded asynchronously, and the program tried to read the image dimensions before it was loaded. I used HMR's comment to further research the onload() handler and modified the readImageDimensions() like this:
function readImageDimensions(data) {
var image = new Image();
console.log(data);
image.onload = function () {
width = image.width;
height = image.height;
items.push({
src: data,
w: width,
h: height
});
}
image.src = data;
}
This way, the onload() gets "primed" with reading the width and height, and won't do that until the whole image data is loaded onto the browser cache. The code also pushes the data onto the items[] array and obviously I'll rename the method into something better, like setImageDataForGallery().

how to implement automatic sliding images through array in javascript

I want to implement sliding images as soon as the website loads.
Here's my html code
<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>
And here's my javascript
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{ x=x+1
if(x>4)
x=1
document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
var t=setInterval("images()",3000);
}
Help will be appreciated.
Although you mentioned "sliding" your initial code looked liked you wanted to swap the images over time.
I admit you may struggle to find good resources on JavaScript for something so simple, which Is why I can relate to your question.
Ok so here's a quick & dirty but more modern-ish image changing slide requestAnimationFrame:
https://jsfiddle.net/julienetienne/95tqftnk/4/
The same principals apply for making images slide except you are pre-loading all images and shifting the position by the slide show width.
var speed = 3;
// Your image array
var images = [
'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];
// Get the slideShow tag
var slideShow = document.getElementById('slide-show');
// Create the image tag //You could also just make one in HTML and get the tag
var img = document.createElement('img');
// Append the image to the slideshow container
slideShow.appendChild(img);
// Basic request animation polyfill
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
return setTimeout(callback, 1000 / 60);
};
// declare var count outside of rAF loop
var count;
function changeImage(timeStamp) {
count = Math.floor(timeStamp / 1000 / speed);
while (count > images.length -1) {
count -= images.length;
}
img.src = images[count];
rAF(changeImage);
}
rAF(changeImage);
img {
width: 600px;
height auto;
}
<div id="slide-show"></div>

draw image from canvas constructor prototype

I'm trying to preload a set of images and draw first one from the list on to multiple canvases using canvas constructor.
It seems I can't even start loading images using prototype function. Console log says this.setImages is not a function. I'm just starting with js therefore it might be a very simple mistake.
I left some comments in the code i hope it will make it a bit clear.
There're other ways to achieve what I'm asking but in my case i have to use constructor function.
var sources = [
'http://i.telegraph.co.uk/multimedia/archive/02830/cat_2830677b.jpg',
'http://r.ddmcdn.com/w_622/u_0/gif/05-kitten-cuteness-1.jpg',
'http://simplycatbreeds.org/images/Kitten.jpg'];
var images = [];
var canvas1 = new canvas('canvas1');
var canvas2 = new canvas('canvas2');
// load images using callback function
setImages(sources, function(images){
window.alert("Done loading... Start!");
this.draw();
});
// canvases constructor
function canvas(canvasId) {
this.canvas = document.getElementById(canvasId);
this.context = this.canvas.getContext('2d');
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
this.canvasId = canvasId;
this.setImages();
};
// preloading images
canvas.prototype.setImages = function(sources, callback){
var cnt = 0;
function imagesLoaded(){
cnt++;
if (cnt >= sources.length){
// passing the objet containing images to load as parameteres
callback(images);
}
}
for (var i=0; i<sources.length; i++) {
images[i] = new Image();
images[i].src = sources[i];
images[i].onload = function(){
imagesLoaded();
}
}
};
canvas.prototype.draw = function() {
// some code to manipulate image to be added here...
this.context.drawImage(images[1], 0, 0);
};
here is FIDDLE example
There are some things I have fixed.
First, I have moved the code that creates the two objects to the end of the JS. The reason is that the prototype functions must be loaded before you try to access them. I recommend using a event listener such as window.onload to prevent the code from starting before everything is loaded.
Second, I changed the setImage so it is called on the canvas objects.
var sources = [...];
var images = [];
// load images using callback function
// canvases constructor
function canvas(canvasId) {
this.canvas = document.getElementById(canvasId);
this.context = this.canvas.getContext('2d');
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
this.canvasId = canvasId;
//I removed this since it does not have the right params
//this.setImages();
};
// preloading images
canvas.prototype.setImages = function(sources, callback){
var cnt = 0;
var obj = this;
function imagesLoaded(){
cnt++;
if (cnt >= sources.length){
// passing the objet containing images to load as parameteres
callback(images, obj);
}
}
for (var i=0; i<sources.length; i++) {
images[i] = new Image();
images[i].src = sources[i];
images[i].onload = function(){
imagesLoaded();
}
}
};
canvas.prototype.draw = function() {
// some code to manipulate image to be added here...
this.context.drawImage(images[1], 0, 0);
};
var canvas1 = new canvas('canvas1');
canvas1.setImages(sources, function(images){
window.alert("Done loading... Start!");
this.draw();
});
var canvas2 = new canvas('canvas2');
canvas2.setImages(sources, function(images, obj){
window.alert("Done loading... Start!");
obj.draw();
});
Demo
Try moving setImages function inside canvas function like this:
function canvas(canvasId)
{
this.setImages = function(...){ };
...
this.setImages();
}
In line 13 you should call setImages on a canvas object: canvas1.setImages();

javascript drawImage() issues

Currently having some issues with drawImage();. Namely it wont actually draw. I tried it out with fillRect(); and it worked aswell as putting the drawImage(); inside the the onload function aswell (which worked).
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 400;
document.body.appendChild(canvas);
var tileArray = [
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,0,0,1,0,0,0],
[0,0,0,1,1,1,1,0,1,1,1,0,0],
[0,0,0,1,1,1,0,0,0,0,1,1,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,0,1,1,1,0,0,0,0,0],
[0,0,0,0,0,0,1,1,0,0,0,0,0]
];
var grassReady = false;
var grass = new Image();
grass.onload = function() {
grassReady = true;
};
grass.src = "images/grass.png";
var sandReady = false;
var sand = new Image();
sand.onload = function() {
sandReady = true;
};
sand.src = "images/sand.png";
var posX = 0;
var posY = 0;
if(grassReady) {
ctx.drawImage(grass, posX, posY);
}
Any pointers as to why this is would be greatly appreciated and I appologize in advance if messed up the code section in anyway. I went through other similar posts and coulden't find a solution that seemed to work.
As #Suman Bogati correctly says, you must wait for your images to load before using them in drawImage.
A Demo: http://jsfiddle.net/m1erickson/jGPGj/
Here's an image loader that preloads all images and then calls the start() function where you can use drawImage because all the images are fully loaded.
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("images/grass.png");
imageURLs.push("images/sand.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// grass.png is in imgs[0]
// sand.png is in imgs[1]
}
This statement ctx.drawImage(); should be inside the grass.onload = function() {} function, something like
grass.onload = function() {
ctx.drawImage(grass, posX, posY);
}
If you define drawImage() outside the grass.onload() function, then that statment would executed first, so at that point grassReady is false, So the condition is not satisfied.
Bascially it's related to asynchronous concept.
Your code is running into order
1) First
var grassReady = false;
if(grassReady) {
//grassReady is false, this condition is not satisfied
ctx.drawImage(grass, posX, posY);
}
2) Second
grass.onload = function() {
grassReady = true;
};

Delay function until an asset has loaded?

I am playing with the canvas, and it seems to be working great in FF6, but in Chrome 13, the sprite that I am drawing does not appear reliably. I have done some research and found that the problem stems from the function firing before the asset has loaded completely.
Fiddle here:
http://jsfiddle.net/LqHY9/
Relevant Javascript:
function sprite(ipath, sh, sw, ih, iw){
/* BASIC INFO FOR SPRITE */
this.frameWidth = sw;
this.frameHeight= sh;
frame_rows = ih/sh;
frame_columns = iw/sw;
num_frames = frame_columns*frame_rows ;
this.frame = new Array();
frameNumber = 0;
for(row = 0; row<frame_rows; row++){
for(i=0;i<frame_columns;i++){
this.frame[frameNumber] = {};
this.frame[frameNumber].offsetX = this.frameWidth*i;
this.frame[frameNumber].offsetY = this.frameHeight*row;
frameNumber++
}
}
this.sheight = sh;
this.swidth = sw;
this.raw = new Image();
this.raw.src = ipath;
}
animation=new sprite("http://www.melonjs.org/tutorial/tutorial_final/data/sprite/gripe_run_right.png",64,64,64,512);
context.drawImage(animation.raw, animation.frame[0].offsetX, animation.frame[0].offsetY, animation.frameWidth, animation.frameHeight, 0, 0, animation.frameWidth,animation.frameHeight)
(Don't worry, my context variable is defined, I just cut that bit out, you can see the whole thing in the JSFiddle.)
The Image object has an onload event which you should hook into.
Assuming you have more than one image, you could implement a sort of a "loader". This would basically just take an array of image URLs, load each of them, and listen to their onload events. Once each image has loaded, it would in turn call some other function, which would signal that every resource has finished loading.
the Image() object has an onload(and onerror) event. If you need to execute something after it loads you can attach a function.
e.g.
var img = new Image();
img.onload = function() {
//do something
};
Just make sure you attach the onload before setting the src.
You need to use the onload handler for the image. You must set the handler before you set the .src for the object because in some browsers, the load event may fire immediately upon setting .src if the image is in the browser cache. Here's a piece of pseudo code:
var img = new Image();
img.onload = function () {
// image is now loaded and ready for handling
// you can safely start your sprite animation
}
img.src = "xxx";
You can see related sample code from another answer I wrote here: jQuery: How to check when all images in an array are loaded?.
function Sprite(urls, speed, box)
{
var that = this, running = false, interval = 0, loaded = false;
that.urls = urls;
that.speed = speed;
that.images = new Array();
that.box = box || { x: 0.0, y: 0.0, w: 64, h: 64 };
for(var i = 0; i < that.urls.length; ++i)
{
that.images[i] = new Image();
that.images[i].src = that.urls[i];
that.images[i].id = i;
var len = that.urls.length;
that.images[i].onload = function(){ if(parseInt(this.id) === len) { loaded = true; } };
}
that.current = 0;
var Draw = function(ctx)
{
if(loaded)
{
var curr = that.images[that.current];
ctx.drawImage(curr, 0.0, 0.0, curr.width, curr.height, that.box.x, that.box.y, that.box.w, that.box.h);
}
};
that.Run = function(ctx)
{
if(!running)
{
running = true;
interval = setInterval(function(){
Draw(ctx);
if(that.current < that.urls.length)
{
that.current++;
}
else
{
that.current = 0;
}
}, that.speed);
}
};
that.Clear = function()
{
if(running)
{
running = false;
clearInterval(interval);
}
};
}
// Exemple
var test = new Sprite(["image1.png", "image2.png", "image3.png"], 250);
test.Run(myContext);

Categories