I have this code
var a = new Image();
a.src = objects.a.image;
var b = new Image();
b.src = objects.b.image;
var x = new Image();
x.src = objects.x.image;
I have about 10 images like this, is there any better way to load it into variables?
This should work
for(var i in objects)
{
if(objects[i].image)
{
var oImage = new Image();
oImage.src = objects[i].image;
// if you need the Image object you can store it somewhere
objects[i].oImgObject = oImage;
}
}
Assuming objects contains just images, try this:
var imageList = [];
for (var i in objects) {
var obj = objects[i];
var img = new Image();
img.src = obj.image;
imageList.push(img);
}
You normally would use an array to store your images.
For example :
var arr = [];
for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
var img = new Image();
img.src = objects[String.fromCharCode(c)].image;
arr.push(img);
}
If you really need to add them as variables to the global context, you might do this :
for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
var img = new Image();
var name = String.fromCharCode(c);
img.src = objects[name].image;
window[name] = img; // better use somthing's else than window...
}
Note that depending on what really is objects, there might be a more straightforward solution.
You can iterate through the properties of your objects object. Creating a new image per iteration, giving it the source of the property on your objects. Then adding it to the array:
Demo
var arrayOfImg = [];
for(var propt in objects){
var image = new Image();
image.src = objects[propt].image;
arrayOfImg.push(image)
}
console.log(arrayOfImg);
Related
this is my problem: im trying to create an image selector, i mean a collection of images shown on the screen among which i can choose one and store it in a var. This is the code for the array:
<script typre="text/javascript">
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
document.write(img[i]);
};
</script>
When i run it, it displays [object HTMLImageElement] instead of the image! What should i do?? Thanks all!
Because img[i] is an object and document.write will write it as string representation of it by calling img[i].toString().
If you want to display an image then use
for (var i = 0; i < img.length; i++) {
document.body.appendChild(img[i]);
};
var img = new Image();
img.src = "../images/poggiatesta2.jpg";
document.write(img.outerHTML);
Use the outerHTML property in order to display it
It is obvious because for loop will print img[0],img[1] not src of image
You can write img[i].src
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
alert(img[i].src);
};
I'm in the middle of changing some existing javascript code which exports images inside a HTML document to a word document. The new functionality is going to capture canvas data inside HTML, convert it to .png and then export however I'm getting 'Cannot set property 'src' of null' when the code reaches this part:
//Capture all canvas data
var canvasData = markup.find('canvas');
var tempImage = new Image();
////Array to hold of the images
var imageArray = Array();
for (var i = 0; i < canvasData.length; i++) {
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
tempImage = null;
}
Any help would be greatly appreciated!
As you can see you are nullifying tempImage inside the loop, after the first iteration it will be assigned a null value, so in the next iteration you'll be trying to set the src for null. that is why you are getting this error. Take var tempImage = new Image(); inside the loop.
for (var i = 0; i < canvasData.length; i++) {
var tempImage = new Image();
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
tempImage = null;
}
Move your var tempImage = new Image(); to inside the loop. Something like
for (var i = 0; i < canvasData.length; i++) {
var tempImage = new Image();
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
// not really required
// tempImage = null;
}
I want to draw image array with drawImage after all the images are loaded.There is a render problem with drawImage(), tried to solve with setTimeout() but its not working all the time.
Here is my code;
while(FocusItem.length>0)
{
FocusItem.pop();
}
ftx=canvas.getContext('2d');
focusImageBackground = new Image();
focusImageBackground.src = "./images/odaklanma/odaklanmaBackground.jpg";
if(RandomSoru==15)
finishSoru=true;
if(finishSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
tempRandomSoru=RandomSoru;
}
if(RandomSoru==tempRandomSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
}
var soru = new Object();
soru["image"] = new Image();
soru.image.src = './images/odaklanma/level/'+RandomSoru+'/soru.png';
soru["x"] = 341;
soru["y"] = 140;
FocusItem.push(soru);
var dogru = new Object();
dogru["image"] = new Image();
dogru.image.src = './images/odaklanma/level/'+RandomSoru+'/dogru.png';
dogru["x"] = xDogru;
dogru["y"] = 280;
FocusItem.push(dogru);
var yanlis = new Object();
yanlis["image"] = new Image();
yanlis.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis.png';
yanlis["x"] = xYanlis1;
yanlis["y"] = 280;
FocusItem.push(yanlis);
var yanlis2 = new Object();
yanlis2["image"] = new Image();
yanlis2.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis1.png';
yanlis2["x"] = xYanlis2;
yanlis2["y"] = 280;
FocusItem.push(yanlis2);
}
if(focusImageBackground.complete){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
else
focusImageBackground.onload=function(){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
function drawFocus(){
ftx.drawImage(focusImageBackground,0,0);
for (var i=0; i<FocusItem.length; i++){
FocusItem[i].image.onload=function(){
ftx.drawImage (FocusItem[i].image, FocusItem[i].x, FocusItem[i].y);
}
}
}
I'd suggest loading all your images, then when they are all done, you can call the rest of your code. I don't quite follow what you're trying to do with all the rest of your code, but here's a simple way to load an array of image URLs and know when they are done.
This is the general idea (I've left out lots of your code that has nothing to do with the central issue of knowing when all the images are loaded) and I've also tried to DRY up your code:
function createImagesNotify(srcs, fn) {
var imgs = [], img;
var remaining = srcs.length;
for (var i = 0; i < srcs.length; i++) {
img = new Image();
imgs.push(img);
img.onload = function() {
--remaining;
if (remaining == 0) {
fn(srcs);
}
};
// must set .src after setting onload handler
img.src = srcs[i];
}
return(imgs);
}
// here's your starting array of filenames
var fnames = ["soru.png", "dogru.png", "yanlis.png", "yanlis1.png"];
// insert your process to create RandomSoru here
var randomSoru = ....;
// build full urls array
var urls = [];
for (var i = 0; i < fnames; i++) {
urls.push('./images/odaklanma/level/' + RandomSoru + '/' + fnames[i]);
}
// load all images and call callback function when they are all done loading
var imgs = createImagesNotify(urls, function() {
// all images have been loaded here
// do whatever you want with all the loaded images now (like draw them)
});
This code is based on an earlier answer of mine here: Cross-browser solution for a callback when loading multiple images?
i have an array(allArr) of arrays on a function,first time array from position 0 from allArr is taken with image from position 0 from another array with images (named image) 'cause of document.ready then by clicking on a button (id="nextimageandshuffle") arrays from allArr and images from image array reach fifth.My problem is that everytime i click on next button i must clear with empty() the div(id="array") where arrays from allArr are added with append() but i cant stop it after 5th array so the 5th image (from image array) remains there but 5th array (from allArr) its deleted...
Heres my code :
var allArr;
var contor = 0;
var i = 0;
$(document).ready( function() {
var arr = new Array("images/alfabet/w.png", "images/alfabet/f.png", "images/alfabet/v.png", "images/alfabet/a.png", "images/alfabet/b.png", "images/alfabet/p.png", "images/alfabet/o.png", "images/alfabet/r.png");
var baiat = new Array("images/alfabet/p.png", "images/alfabet/b.png", "images/alfabet/a.png", "images/alfabet/aa.png", "images/alfabet/i.png","images/alfabet/a.png", "images/alfabet/t.png");
var colac = new Array("images/alfabet/g.png", "images/alfabet/c.png", "images/alfabet/u.png", "images/alfabet/o.png", "images/alfabet/l.png", "images/alfabet/a.png", "images/alfabet/c.png");
var slapi = new Array("images/alfabet/s.png", "images/alfabet/ss.png", "images/alfabet/l.png", "images/alfabet/a.png", "images/alfabet/b.png", "images/alfabet/p.png", "images/alfabet/i.png", "images/alfabet/i.png");
var umbrela = new Array("images/alfabet/u.png", "images/alfabet/n.png", "images/alfabet/m.png", "images/alfabet/p.png", "images/alfabet/b.png", "images/alfabet/r.png", "images/alfabet/e.png", "images/alfabet/l.png", "images/alfabet/a.png");
allArr = new Array(arr, baiat, colac, slapi, umbrela);
for(i=0; i<allArr[0].length; i++)
{
var img = new Image();
img.src = allArr[0][i];
$('#array').append(img);
}
});
var image = new Array("images/baiat.png", "images/colac.png" , "images/slapi.png" , "images/umbrela.png");
var imgNumber=0;
var numberOfImg = image.length;
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++;
}
document.slideImage.src = image[imgNumber-1];
contor++;
$("#array").empty();
for(i = 0; i<allArr[contor].length; i++)
{
var img = new Image();
img.src = allArr[contor][i];
$('#array').append(img);
}
}
if(document.images){
var image1 = new Image();
image1.src = "images/vapor.png";
var image2 = new Image();
image2.src = "images/baiat.png";
var image3 = new Image();
image3.src = "images/colac.png";
var image4 = new Image();
image4.src = "images/slapi.png";
var image5 = new Image();
image5.src = "images/umbrela.png";
}
HTML:
<img src="images/vapor.png" name="slideImage" class='secondcanvas' width='450' height='300' alt="">
<div id="array" class='thirdcanvas'></div>
<img id="nextimageandshuffle" src="images/nextBtn.png" title="Continuare" >
I'm not sure if I fully understand what you are trying to do, but I think I got it...
You will need to determine if you are on the last image or not, because if your not you still want to empty the element. Compared the current images src to the string in allArr[4][4] and if they match, don't do the .empty(). So instead of just:
$("#array").empty();
You will want to replace it with something like:
if(img.src == allArr[4][4]){
return;
}else{
$("#array").empty();
}
Not sure if I really understood what your problem is. However if you want to keep the last image in your div tag after calling empty(), you just have to append it again :
$("#array").empty();
var lastImage = new Image();
lastImage.src = allArr[4][4];
$("#array").append(lastImage);
Please tell me if this helps or not.
I have the following class for which I wish to create a series of instances:
function rashnik(size, name) {
var img = document.createElement('img');
img.src = "pics/"+name+".jpg";
img.height = size;
img.width = size;
img.id = name;
d = 300-size;
img.style.marginBottom = d/2;
img.style.marginLeft = 50;
var gal = document.getElementById("gallery");
gal.appendChild(img);
};
Now, Iv'e created this function to create the instances:
function creater(names) {// the argument "names" would be a two-dimensional array
for (var a = 0; a < names.length; a++){
var names[a][0] = new rashnik(names[a][1], names[a][0]); // right here is where I get the error
}
}
And this is how I try to call it:
var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
creater(friends);
The thing is, the var names[a][0] part throws me an error, which I totally understand; I want to create an object whose name is the same as the string stored in names[a][0], but, well, it just doesn't work that way.
Does anyone have an idea as to what I could to to make it happen?
Cleaned up. I think this is doing what you want:
Create a new class instance in the loop, so it's an object
Put something in that object. I put the img in as an example.
Use the name as the "key" of a returning object. I access that in the alert in the code below by using resultsView['adi'] but could have also done resultsView.Adi
http://jsfiddle.net/w7wKW/
function rashnik(size, name)
{
var img=document.createElement('img');
img.src = "pics/"+name+".jpg";
img.height = size;
img.width = size;
img.id = name;
d = 300-size;
img.style.marginBottom = d/2;
img.style.marginLeft = 50;
var gal = document.getElementById("gallery");
gal.appendChild(img);
this.img = img;
return this;
};
function creater(names)
{//the argument "names" would be a two-dimensional array
var results = { };
for(var a=0; a<names.length; a++)
{
results[names[a][0]] = new rashnik(names[a][1], names[a][0]);
}
return results;
}
var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
var resultsValue = creater(friends);
alert(resultsValue['adi'].img.src);