Preloading images with javascript does not work - javascript

I'm trying to preload images with javascript:
$(document).ready(function () {
preloadImages(
['../../Content/Resources/close_mouse_over.png',
'../../Content/Resources/close.png']);
});
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i];
}
}
function mouseOverForImage(imgId, imgSrcs) {
document.getElementById(imgId).src = imgSrcs;
}
In Html:
<input type="image" src="../../Content/Resources/close.png" name="Action" value="Save" onmouseover="mouseOverForImage('close', '../../Content/Resources/close_mouse_over.png')"
onmouseout = "mouseOverForImage('close', '../../Content/Resources/close.png')" id="close" title = "Close" />
But request is still sending to server after mouseover. Is not working only in chrome

As noted within my comment, you are passing an array of arrays to the preLoadImages method.
As a result, you are passing an array to image[i].src which means it won't get loaded.
Try
$(document).ready(function () {
preloadImages(
['../../Content/Resources/close_mouse_over.png', '../../Content/Resources/close.png']);
});
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i];
}
}
function mouseOverForImage(imgId, imgSrcs) {
document.getElementById(imgId).src = imgSrcs;
}
or, if you want to keep the array of array's, then use
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i][0];
}
}
Edit, on further investigation, a possible cause is preloadImages destroys the image array after preloading the images.
try this instead:
function preloadImages(sources) {
window.preloadedImages = new Array();
for (var i = 0; i < sources.length; i++) {
window.preloadedImages[i] = new Image();
window.preloadedImages[i].src = sources[i];
}
}
This stores the preloaded images within the window object, allowing them to preload properly.
Hope that helps?

Related

Javascript image width is 0 on load

I have this code for loading several images:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(i){
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded(image);
}
}
onload = loadAssets();
but when I try to access the images in the load() functions, it says the width and height are 0, for me indicating the images aren't finished loading, but they should be? I'm dumbfounded...
The problem is this line:
image.onload = imageLoaded(image);
Because you have the parenthesis, Javascript calls the function immediately and expects it to return the result that will be passed to the onload
You need something like this:
const imageURLS = ["lvls/1.png", "assets/tileatlas.png"];
let imageCount = imageURLS.length;
let assets = [];
function imageLoaded(){
var i = this
imageCount--;
if(imageCount == 0){
window.TILEATLAS = assets[0];
load();
}
}
function loadAssets(){
for(let i = 0, len = imageCount; i < len; i++){
let image = new Image();
image.src = imageURLS[i];
assets.push(image);
image.onload = imageLoaded.bind(image);
}
}
onload = loadAssets();
The bind function sets the value of this in the function to the argument. This way, it won't call the function, but create it.

In JavaScript, Displaying pictures from an array?

I am making an rpg game. So I am trying to make a for loop that will generate buttons to the screen this what I have so far,
$(document).ready(function() {
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'assets/images/young_link.jpg';
//var test = "<img src= '../images/young_link.jpg'>";
//var young_hero = ["young_link","young_zelda","impa", "malon"];
var young_hero = ["young_link"];
//var hero_images = [test];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<buttons>");
hero_btns.addClass("hero");
hero_btns.attr("data-hero" , young_hero[i]);
hero_btns.attr("data-image" , imgArray[i]);
hero_btns.text(imgArray[i]);
hero_btns.text(young_hero[i]);
$("#buttons").append(hero_btns);
}
});
The problem is that it is not putting the image on the button.
In order to add an image to your button, you will have to do more than just data-image, You will need to actually create an <img> tag and give it the source of the image. Then you will need to use css to get the image lined up properly in your button.
I have updated your code to add the image to the first button.
$(document).ready(function() {
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT7o2tCpqvs_XRpvtHbuRe9KwkzydiVhWLJ6YVTkQcpkev09w0MBCgNu2w';
//var test = "<img src= '../images/young_link.jpg'>";
var young_hero = ["young_link","young_zelda","impa", "malon"];
//var young_hero = ["young_link"];
//var hero_images = [test];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>"); // changed from <buttons>
hero_btns.addClass("hero");
hero_btns.attr("data-hero" , young_hero[i]);
//hero_btns.text(imgArray[i]);
hero_btns.text(young_hero[i]);
hero_btns.append(imgArray[i])
$("#buttons").append(hero_btns);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
</div>
Not sure about your exact requirement. Seems you are trying to create a button inside another button.
If you want to add an image use img tag and its src attribute
Not tested but you can try this
$(document).ready(function() {
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'assets/images/young_link.jpg';
var young_hero = ["young_link"];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<img>");
hero_btns.addClass("hero");
hero_btns.attr("data-hero", young_hero[i]);
hero_btns.attr("src", imgArray[i]);
hero_btns.text(imgArray[i]);
hero_btns.text(young_hero[i]);
$("#buttons").append(hero_btns);
}
});
$(function(){
var heroList = {
{heroName: "young_link", imagePath: "assets/images/young_link.jpg"},
{heroName: "young_zelda", imagePath: "assets/images/young_zelda.jpg"},
{heroName: "impa", imagePath: "assets/images/impa.jpg"},
{heroName: "young_link1", imagePath: "assets/images/young_link1.jpg"}];
for (var i = 0; i < heroList.length; i++) {
var hero_btns = $('<img class="hero">');
hero_btns.attr({
"data-index": i,
"src": heroList[i].imagePath,
"data-name": heroList[i].heroName,
"title": heroList[i].heroName
});
$("#buttons").append(hero_btns);
}
})
You can use this simple on jsfiddle example.

How to Change the Source of an Image W/JS

I have to change the src of an image using java script and I am pretty sure i hit a road block, in the html I have 3 li elements and in the id is the source of the mouseenter img. I feel like I am close but so far. Heres my code so far. Thanks for any help!
Javascript:
var $ = function (id) {
return document.getElementById(id);};
window.onload = function () {
var links = document.getElementsByTagName("li"),
imgElements = document.getElementsByTagName("img"),
imgNode,
i,
URLone,
URLtwo,
link,
image;
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
}
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
HTML ::
<body>
<section>
<h1>Ram Tap Combined Test</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
Working jQuery :
$(document).ready(function() {
$("#image_rollovers img").each(function() {
var oldURL = $(this).attr("src"); // gets the src attribute
var newURL = $(this).attr("id"); // gets the id attribute
// preload images
var rolloverImage = new Image();
rolloverImage.src = newURL;
$(this).hover(
function() {
$(this).attr("src", newURL); // sets the src attribute
},
function() {
$(this).attr("src", oldURL); // sets the src attribute
}
); // end hover
}); // end each
}); // end ready
for (i = 0; i < imgElements.length; i++) {
(function(imgNode) {
imgNode.addEventListener("mouseenter", function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}, false);
imgNode.addEventListener("mouseout", function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
}, false);
})(imgElements[i]);
}
A couple of problems in your code.
First for loop closing right away, instead should close after your
imgNode.mouseout function
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
}
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
Last for loop runs 6 times but there are only 3 tags in html. When it coming to loop no. 3 it doesn't get any value for link.src.
Also links variable provides a collection of 'li' tags and not 'img', last for loop requires src from link.src which doesn't have any value, need to change
var links = document.getElementsByTagName("li"),
to
var links = document.getElementsByTagName("img"),
Try that. Hopefully after correcting above errors your code should work.

Why can't i access the x variable of the bitmap? (javascript)

I'm trying to loop through 3 images in my array and add it to the stage (using easelJS). I want to position it as well. When I try to access the images in the array i get an error saying that the I can't set x of undefined. Why can't the x variable of the easeljs Bitmap be accessed?
function displayPosters() {
getPosters(); //get all images and assign it to designated array
console.log(frontPosters);
console.log(frontPosters.length);
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}
here is the code for loading and pushing those images into the frontPosters arrray.
var frontPosters = new Array(3);
function getPosters() {
var games = new Image(); //create 3 images
var apps = new Image();
var aboutme = new Image();
games.onload = function() { //add image to frontImages array on load
var gamesPost = new createjs.Bitmap(games);
frontPosters[0] = gamesPost;
};
apps.onload = function() {
var appPost = new createjs.Bitmap(apps);
frontPosters[1] = appPost;
};
aboutme.onload = function() {
var amPost = new createjs.Bitmap(aboutme);
frontPosters[2] = amPost;
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
Using for(poster in frontPosters) is bad practice, because you're actually iterating over the Array Object and not the values (a.k.a. the Array itself). Use for(var i=0; i<frontPosters.length; i++) instead. It's the easiest solution, IMO.
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
Edit
I think you are dealing with a race-condition. You are going over your array before all images were loaded. By setting var frontPosters = new Array(3); you automatically set three values to undefined which are pushed into the new array.
You should check that all images were loaded before proceeding with the script.
Here's an idea for you. Set a callback that will run only after the third image was loaded.
var frontPosters = new Array(3);
function getPosters(callback) {
var games = new Image(),
apps = new Image(),
aboutme = new Image(),
loaded = 0;
games.onload = function() {
frontPosters[0] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
apps.onload = function() {
frontPosters[1] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
aboutme.onload = function() {
frontPosters[2] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
function displayPosters() {
getPosters(function() {
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}); //get all images and assign it to designated array, only after all images were loaded
}

Preloading images and adding class

I am using the following code to preload my images:
function preload(sources)
{
var images = [];
for (i = 0, length = sources.length; i < length; ++i) {
images[i] = new Image();
images[i].src = sources[i];
}
}
How can I add a class to the image object? I tried images[i].class = 'classname', but this doesn't do the trick. Any suggestions?
Thanks!
Use className instead of class.
images[i].className = "className";

Categories

Resources