'Sounds' folder not loading correctly to localhost - javascript

Good afternoon,
I've been following this tutorial to make a simple (!) html5 canvas game. I've been using the error console on Safari to help troubleshoot, but I can't figure this one out; I have an 'img' folder, containing all artwork, and a 'sounds' folder, containing all sounds.
All assets are loaded with the assetLoader and checked before the page loads - if something is missing or labelled incorrectly, it won't load.
The sounds 'do' play - the theme music runs fine, and sound effects trigger approx 60% - 70% of the time (jump sound, collide sound etc) but the folder hasn't loaded correctly. If I check the 'resources' tab, 'sounds' is now called 'Other', and if I click on any of the mp3's in that folder, I get the message 'An error occurred trying to load the resource'.
The assetLoader part of the code looks like this:
var assetLoader = (function() {
this.sounds = {
'bg' : 'sounds/theme.mp3',
'jump' : 'sounds/fart.mp3',
'gameOver' : 'sounds/gameOver.mp3',
'ding' : 'sounds/ding.mp3'
};
Then I have a var to check the total number of sound assets:
var numSounds = Object.keys(this.sounds).length;
Then I have this function to check the state:
function _checkAudioState(sound) {
if (this.sounds[sound].status === 'loading' && this.sounds[sound].readyState === 4)
{ assetLoaded.call(this, 'sounds', sound);
}
}
Finally, I have a downloadAll function that looks like this:
this.downloadAll = function() {
var _this = this;
var src;
for (var img in this.imgs) {
if (this.imgs.hasOwnProperty(img)) {
src = this.imgs[img];
(function(_this, img) {
_this.imgs[img] = new Image();
_this.imgs[img].status = 'loading';
_this.imgs[img].name = img;
_this.imgs[img].onload = function() { assetLoaded.call(_this, 'imgs', img) };
_this.imgs[img].src = src;
})(_this, img);
}
}
for (var sound in this.sounds) {
if (this.sounds.hasOwnProperty(sound)) {
src = this.sounds[sound];
(function(_this, sound) {
_this.sounds[sound] = new Audio();
_this.sounds[sound].status = 'loading';
_this.sounds[sound].name = sound;
_this.sounds[sound].addEventListener('canplay', function() {
_checkAudioState.call(_this, sound);
});
_this.sounds[sound].src = src;
_this.sounds[sound].preload = 'auto';
_this.sounds[sound].load();
})(_this, sound);
}
}
}
return {
imgs: this.imgs,
sounds: this.sounds,
totalAssest: this.totalAssest,
downloadAll: this.downloadAll
};
})();
I've left the images in this block of code as they work fine, and I think the sounds should too, but for some reason they don't. I have read about potential mp3 compatibility problems with browsers and html5 canvas, but as the sounds are playing I'm not sure this is the issue. If anyone can offer any insight, that would be much appreciated.

Related

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

Preloading images to play animation

I have to preload approximately 900 images to play the required animation based on the user selection. But before that, I have to check, which images I have to preload. I have approximately 5400 images, which I have extracted from the videos using ffmpeg. And based on the user selection I have to preload the required images. I am also showing how much percentage of preloading is completed.
Below is the code I am using to preload 900 the images based on the user selection.
function preloadImages(ImagesURL, callback) {
var img_i;
var img_j;
var loaded = 0;
for (img_i = 0, img_j = ImagesURL.length; img_i < img_j; img_i++) {
(function (img, src) {
img.onload = function () {
updateProgress(); // to show how much is completed
if (++loaded == ImagesURL.length && callback) {
callback();
}
};
img.onerror = function () {
showCustomMessage("Error occurred while loading files, please refresh the page and try again.");
};
img.onabort = function () {};
img.src = src;
} (new Image(), ImagesURL[img_i]));
}
}
Now I want to know is there any better method other than this? Or should I use AJAX instead of that, because this function is running absolutely fine on the desktop's but the same method is eating up lot of resources while running on the iPad or handheld devices.

Issue with image load recursive chain on slow network/mobile

So basically I have a page with a few sections. Each sections contains 5-30 image icons that are fairly small in size but large enough that I want to manipulate the load order of them.
I'm using a library called collagePlus which allows me to give it a list of elements which it will collage into a nice image grid. The idea here is to start at the first section of images, load the images, display the grid, then move on to the next section of images all the way to the end. Once we reach the end I pass a callback which initializes a gallery library I am using called fancybox which simply makes all the images interactive when clicked(but does not modify the icons state/styles).
var fancyCollage = new function() { /* A mixed usage of fancybox.js and collagePlus.js */
var collageOpts = {
'targetHeight': 200,
'fadeSpeed': 2000,
'allowPartialLastRow': true
};
// This is just for the case that the browser window is resized
var resizeTimer = null;
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
// Here we apply the actual CollagePlus plugin
var collage = function(elems) {
if (!elems)
elems = $('.Collage');
elems.removeWhitespace().collagePlus(collageOpts);
};
var resetCollage = function(elems) {
// hide all the images until we resize them
$('.Collage .Image_Wrapper').css("opacity", 0);
// set a timer to re-apply the plugin
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
collage(elems);
}, 200);
};
var setFancyBox = function() {
$(".covers").fancybox({/*options*/});
};
this.init = function(opts) {
if (opts != null) {
if (opts.height) {
collageOpts.targetHeight = opts.height;
}
}
$(document).ready(function() {
// some recursive functional funk
// basically goes through each section then each image in each section and loads the image and recurses onto the next image or section
function loadImage(images, imgIndex, sections, sectIndex, callback) {
if (sectIndex == sections.length) {
return callback();
}
if (imgIndex == images.length) {
var c = sections.eq(sectIndex);
collage(c);
images = sections.eq(sectIndex + 1).find("img.preload");
return loadImage(images, 0, sections, sectIndex + 1, callback);
}
var src = images.eq(imgIndex).data("src");
var img = new Image();
img.onload = img.onerror = function() {
images[imgIndex].src = src; // once the image is loaded set the UI element's source
loadImage(images, imgIndex + 1, sections, sectIndex, callback)
};
img.src = src; // load the image in the background
}
var firstImgList = $(".Collage").eq(0).find("img.preload");
loadImage(firstImgList, 0, $(".Collage"), 0, setFancyBox);
});
}
}
From my galleries I then call the init function.
It seems like my recursive chain being triggered by img.onload or img.onerror is not working properly if the images take a while to load(on slow networks or mobile). I'm not sure what I'm missing here so if anyone can chip in that would be great!
If it isn't clear what is going wrong from the code I posted you can see a live example here: https://www.yuvalboss.com/albums/olympic-traverse-august-2017
It works quite well on my desktop, but on my Nexus 5x it does not work and seems like the finally few collage calls are not happening. I've spent too long on this now so opening this up to see if I can get some help. Thanks everyone!
Whooooo I figured it out!
Was getting this issue which I'm still unsure about what it means
[Violation] Forced reflow while executing JavaScript took 43ms
Moved this into the callback that happens only once all images are loaded
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
For some reason it was getting called early even if the browser never resized causing collage to get called when no elements existed yet.
If anyone has any informative input as to why I was getting this js violation would be great to know so I can make a better fix but for now this works :):):)

How can i play a gif like 9 gag?

http://www.9gag.com
I want pause and play a gif,like the 9gag,
how can i do that?
I know I have to use one. Jpg and. Gif but I tried a few things but did not work
I found this function
function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}
function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
} catch(e) { // cross-domain -- mimic original with all its tag attributes
for (var j = 0, a; a = i.attributes[j]; j++)
c.setAttribute(a.name, a.value);
i.parentNode.replaceChild(c, i);
}
}
function unfreeze_gif(id, src) {
i = document.getElementById(id);
i.src = src;
}
but i dont know how to use on the HTML
Can someone give me an example? with HTML , CSS E JS (or Jquery) ?
Thanks
It's just 2 versions of the image: One static JPG, one moving GIF.
Here's a fiddle that mimic the behaviour: http://jsfiddle.net/bortao/QADeM/
JS
$(".gif-post").on("click", function () {
var $this = $(this);
var img = $this.find("img"); // Find the image element
if (!this.playing) {
this.playing = true; // Set or create a variable
img.attr("src", img.attr("src").replace(".jpg", "a.gif"));
$this.find(".play").hide(); // Hide the overlay
} else {
this.playing = false;
img.attr("src", img.attr("src").replace("a.gif", ".jpg"));
$this.find(".play").show();
}
});
I was actually working on a 9gag clone myself, so i was searching as well for a gif player.
You can use this one: http://freezeframe.chrisantonellis.com/
All you have to do for this one is include the javascript and in the .gif link and add the following class: "freezeframe"
There is also this one: http://quickleft.com/blog/embeddable-animated-gifs-with-controls-just-in-time-for-christmas
I haven't used it, but it seems very interesting.

Internet explorer dynamic image loading

I am trying to load images throught javascript. Different browser than IE8 or ie9 it's working fine, but in IE doesn't. If I load the image directly
http://localhost/_eWar/index.php?road=map&createimage=true
it's working fine, but trought javascript
src="index.php?road=map&createimage=true";
this.img_object.object = $("<img>");
this.img_object.object.unbind('load').
removeAttr("src").
removeAttr("width").
removeAttr("height").
attr("class","map newMap").
attr("usemap","#world").
css({ top: 0, left: 0 }).
load(function(){
me.image_loaded = true;
me.img_object.display_width = me.img_object.orig_width = this.width;
me.img_object.display_height = me.img_object.orig_height = this.height;
if(!me.container.hasClass("iviewer_cursor")){
me.container.addClass("iviewer_cursor");
}
if(me.settings.zoom == "fit"){
me.fit();
}
else {
me.set_zoom(me.settings.zoom);
}
if(me.settings.onFinishLoad)
{
me.settings.onFinishLoad.call(me);
}
//src attribute is after setting load event, or it won't work
}).attr("src",src);
I get a "compatible view" message.
I'm not sure why you're resetting and looking at attributes on a new image.
Here's an easy way to load images:
function loadSample() {
var i = new Image()
i.onload = function() {
alert("loaded")
}
i.src = "http://jsfiddle.net/img/logo.png"
}

Categories

Resources