Preloader with JavaScript - javascript

I have faced such a problem. I need to make a preloader with a percentage for a page but I don't know how. Actually, I don't need animation or simple preloader. What do I can and what do I have?
window.onload = function() {
var images = document.images,
imagesTotalCount = images.length,
imagesLoadedCount = 0,
preloader = document.getElementById('js_preloader'),
percDisplay = document.getElementById('js_preload__percentage');
for(var i = 0; i < imagesTotalCount; i++) {
image_clone = new Image();
image_clone.onload = image_loaded;
image_clone.onerror = image_loaded;
image_clone.src = images[i].src;
}
function image_loaded() {
imagesTotalCount++;
percDisplay.innerHTML = (((100 / imagesTotalCount) * imagesLoadedCount) << 0) + '%';
if(imagesLoadedCount >= imagesTotalCount) {
setTimeout(function() {
if(!preloader.classList.contains('done')) {
preloader.classList.add('done');
}
}, 1500);
}
}
};
This aproach allows to see all images to be downloaded and and calculate percentage. But how do I can also take in count the download of css and js files?

You could use the same approach, but with document.scripts and document.styleSheets collections.

Related

Loading multiple images with javascript

I am strugling to create a script to load multiple images for a game drawn on Canvas. The window seems to load without completing the load of all images. I've tried many ways but none of them seems to work. The function drawGameMenu() is called before the images are actually loaded and so the images are not drawn. If someone could help, I would be grateful. Here is my script, kind regards:
var imageNames = ["menuImage", "resetScoreButton", "instructionsButton", "playButton", "dialogPanel", "gamePlayImage", "exitButton", "timerPanel", "messengerPanel", "scoreBar", "yesButton", "noButton", "goButton"];
var imageFileNames = ["game_Menu", "reset_score_button", "instructions_button", "play_button", "dialog_panel", "game_play", "exit_button", "timer", "messenger_panel", "score_bar", "yes_button", "no_button", "go_button"];
var imageCollection = {};
window.addEventListener("load", function() {
var u = imageNames.length - 1;
for(i = 0; i <= u; i++) {
var name = imageNames[i];
imageCollection[name] = new Image();
imageCollection[name].src = imageFileNames[i] + ".png";
console.log(imageCollection[name]);
imageCollection[name].addEventListener('load', function() {
do {
var x = imageCollection[name].complete;
}
while(x != true);
});
}
drawGameMenu();
});
I made some changes on the script and now it works on the PC browser, but not working on smartphone. The script is the following:
window.addEventListener("load", async function loadImageCollection() {
var u = imageNames.length - 1;
for(i = 0; i <= u; i++) {
var name = imageNames[i];
imageCollection[name] = new Image();
imageCollection[name].src = imageFileNames[i] + ".png";
do {
await new Promise((resolve, reject) => setTimeout(resolve, 50));
x = imageCollection[name].complete;
console.log(x);
}
while(x == false);
}
drawGameMenu();
});
Keep it simple
Just use a simple callback and a counter to count of images as they load. Adding promises adds an additional level of complexity that is just a source of potential bugs. (the promise for each image and its callback and the need to call it on image load, and the need to handle promise.all with another callback)
const imageCollection = loadImages(
["menuImage", "resetScoreButton", "instructionsButton", "playButton", "dialogPanel", "gamePlayImage", "exitButton", "timerPanel", "messengerPanel", "scoreBar", "yesButton", "noButton", "goButton"],
["game_Menu", "reset_score_button", "instructions_button", "play_button", "dialog_panel", "game_play", "exit_button", "timer", "messenger_panel", "score_bar", "yes_button", "no_button", "go_button"],
drawGameMenu // this is called when all images have loaded.
);
function loadImages(names, files, onAllLoaded) {
var i = 0, numLoading = names.length;
const onload = () => --numLoading === 0 && onAllLoaded();
const images = {};
while (i < names.length) {
const img = images[names[i]] = new Image;
img.src = files[i++] + ".png";
img.onload = onload;
}
return images;
}
With the use of promises this becomes a very easy task. I don't know if ES6 allows it, but give it a try anyways.
var jarOfPromise = [];
for(i = 0; i <= u; i++) {
jarOfPromise.push(
new Promise( (resolve, reject) => {
var name = imageNames[i];
imageCollection[name] = new Image();
imageCollection[name].src = imageFileNames[i] + ".png";
console.log(imageCollection[name]);
imageCollection[name].addEventListener('load', function() {
resolve(true);
});
})
)
}
Promise.all(jarOfPromise).then( result => {
drawGameMenu();
});

JS: Determinining image dimensions only partially successful

I'm creating a small webapplication with JS/HTML/CSS where the user has a dropdown menu to choose from 13 different images. Option 1 is default, and when the user chooses a different option the application is refreshed and the dimensions of other objects in the application adjust to the dimensions of the new image.
In order to access the image dimensions (height and width) of the 13 different images an JS loop starts and stores the dimensions in two arrays.
var height_array = []
var width_array = []
for (i = 1; i <= 13;i = i + 1) {
var img = new Image();
if (i <= 9){
img.src = "img/rehe/RE0"+i+"/001.png";
}
else{
img.src = "img/rehe/RE"+i+"/001.png";
}
height_array.push(img.height);
width_array.push(img.width);
}
What I dont understand, is that the loop is sucessfull only part time, at times the arrays are empty or only partially populated. Naturally, the application is then built up all wrong.. A refresh helps in this case, but it is still anoying.
I have a preversion of this very simple application here: http://wieselundco.ch/plenum2/index.html Thanks in advance!
The image has to load before you can get the dimensions
var height_array = []
var width_array = []
for (i = 1; i <= 13;i = i + 1) {
(function(j) {
var img = new Image();
img.onload = function() {
height_array[j] = img.height;
width_array[j] = img.width;
}
if (img.complete) img.onload();
if (j <= 9){
img.src = "img/rehe/RE0"+j+"/001.png";
} else {
img.src = "img/rehe/RE"+j+"/001.png";
}
})(i);
}

A function to preload images - need to draw them now, but how?

I'm dabbling with canvas. And I'm a little lost on something.
I have this function:
function preloadimages(arr) {
var newimages = []
var arr = (typeof arr != "object") ? [arr] : arr
for (var i = 0; i < arr.length; i++) {
newimages[i] = new Image()
newimages[i].src = arr[i]
}
}
And I call it like so:
preloadimages(['images/background.png', 'images/hero.png', 'images/monster.png']);
The only problem is, I don't know how to then draw them again later.
If I was preloading one image inside my js I would say:
var bgOk = false;
var bg = new Image();
bg.onload = function () {
bgOk = true;
};
bg.src = "images/background.png";
and then further down when I wanted it drawn I would say:
if (bgOk) {
context.drawImage(bg, 0, 0);
}
And that would be that. The problem is I have made a preloader class, I don't really know how now to call in just the image I want to draw now, or even how to implement the bgOk idea so that if it loaded ok, I can draw it, and if not, leave it alone.
Could someone advise me on this? I'm basically just trying to go more class based rather than the dirty great mess I normally have with a huge javascript file that is ugly and not as maintainable.
This seems to be a complicated problem, but in reality isn't as bad as it looks. If you want to use pre-existing code, or just want to look at something for ideas you can have a look at: http://thinkpixellab.com/pxloader/ This library was used in the HTML5 version of Cut The Rope.
A simple custom implementation could be something like the following:
function loadImages(arr, callback) {
this.images = {};
var loadedImageCount = 0;
// Make sure arr is actually an array and any other error checking
for (var i = 0; i < arr.length; i++){
var img = new Image();
img.onload = imageLoaded;
img.src = arr[i];
this.images[arr[i] = img;
}
function imageLoaded(e) {
loadedImageCount++;
if (loadedImageCount >= arr.length) {
callback();
}
}
}
And then you can call it like this:
var loader = loadImages(['path/to/img1', 'path/to/img2', 'path/to/img3'], function() {
ctx.drawImage(loader.images['path/to/img1']); // This would draw image 1 after all the images have been loaded
// Draw all of the loaded images
for (var i = 0; i < loader.images.length; i++) {
ctx.drawImage(loader.images[i]);
}
});
If you want more details on asset loading you can have a look at the asset loading section of Udacity's HTML5 Game Development course https://www.udacity.com/course/cs255
A function I use:
function ImageLoader(sources, callback)
{
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
You call it like so:
var sources = {
bg: path/to/img.png,
title: path/to/img/png
};
var _images = {};
isReady = ImageLoader(sources, function(images) {
_images = images;
});
And then to access your images
_images.bg;
Example: drawImage(_images.bg, 0, 0);

Continuous Image Vertical Scroller

I need to adjust the script from http://javascript.about.com/library/blcvert.htm to change direction of scrolling to DOWN.
Could anybody help?
Of course, it would be also helpful if anybody knows/have some other script which produces the same effect.
Thanx
P.S. the script (in readable format is):
var imgAry1 = ['img1.png','img2.png'];
function startCloud() {
new mq('clouds', imgAry1, 380);
mqRotate(mqr);
}
$(document).ready(function() {
startCloud();
});
var mqr = [];
function mq(id, ary, heit) {
this.mqo=document.getElementById(id);
var wid = this.mqo.style.width;
this.mqo.onmouseout=function() { mqRotate(mqr); };
this.mqo.onmouseover=function() { clearTimeout(mqr[0].TO); };
this.mqo.ary=[];
var maxw = ary.length;
for (var i=0;i<maxw;i++) {
this.mqo.ary[i]=document.createElement('img');
this.mqo.ary[i].src=ary[i];
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.top = (heit*i)+'px';
this.mqo.ary[i].style.height = heit+'px';
this.mqo.ary[i].style.width = wid;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j=mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i=0;i<maxa;i++) {
var x = mqr[j].ary[i].style;
x.top=(parseInt(x.top,10)-1)+'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.top,10)+parseInt(y.height,10)<0) {
var z = mqr[j].ary.shift();
z.style.top = (parseInt(z.style.top) + parseInt(z.style.height)*maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO=setTimeout('mqRotate(mqr)',10);
}
On this line:
x.top=(parseInt(x.top,10)-1)+'px';
it says that you take x.top in pixels, parse out the number, subtract one and add the 'px' again. The element's position from top is decreased by 1 each time, so it goes up. All you need to do for it to go down is to add the one.
x.top=(parseInt(x.top,10)+1)+'px';
I also tested this hypothesis on the page you linked :)

Generic Javascript Image Swap

I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}

Categories

Resources