In javascript, creating a class instance in a for loop - javascript

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);

Related

JavaScript cannot find method a second time?

I'm attempting to build a poker game. The method in question is very simple, and it works when it runs the first time.
This part isn't perfect convention because I'm just using it to test my methods:
var $ = function (id) { return document.getElementById(id); };
var test = function() {
var deck = new POKER.Deck();
var hand = new POKER.Hand();
for (var i = 0; i < 7; i++){
hand.addCard(deck.dealCard());
}
hand.sortByRank();
for (var j = 0; j < 7; j++){
var img = document.createElement("img");
var card = hand.getCardAtIndex(j); //** <------- WORKS HERE**
img.src = card.getImage();
$("images").appendChild(img);
}
var testHand = new POKER.Hand();
testHand = hand.removePairs();
for (var k = 0; k < testHand.length; k++) {
var img2 = document.createElement("img");
var card2 = testHand.getCardAtIndex(k); // **<------FAILS HERE**
img2.src = card2.getImage();
$("handImg").appendChild(img2);
}
};
window.onload = function() {
test();
};
The first and second loop work, and the hand is displayed and everything. When it gets to the last loop, the debugger tells me "TypeError: testHand.getCardAtIndex is not a function"
I was attempting to test the removePairs method (to test for straights more easily), and when watching the variables in the debugger, testHand clearly gets populated correctly. The method seems to work just fine.
getCardAtIndex:
POKER.Hand.prototype.getCardAtIndex = function(index) {
return this.cards[index];
};
removePairs:
POKER.Hand.prototype.removePairs = function(){
var allCards = this.cards;
var tempCards = [];
var uniqueRanks = [];
var unique;
for(var i = 0; i < allCards.length; i++){
unique = true;
for(var j = 0; j < uniqueRanks.length; j++){
if(allCards[i].getRank() == uniqueRanks[j]){
unique = false;
break;
}
}
if(unique){
uniqueRanks.push(allCards[i].getRank());
tempCards.push(allCards[i]);
}
}
return tempCards;
};
I'm completely perplexed.
var testHand = new POKER.Hand();
testHand = hand.removePairs();
hand.removePairs() returns an Array, not a Hand object.
That's why you don't have access to the getCardAtIndex method.
If cards is a public property you could do:
testHand.cards = hand.removePairs();
Or you can have a setter method:
testHand.setCards(hand.removePairs);

Cannot set property 'src' of null in JavaScript

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;
}

how to use drawImage after load all images in array

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?

js loading images

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);

Cloned objects and reference inside functions

I am trying to do the following:
var element = {};
element.attrA = 'A';
element.attrB = 1;
element.autoAdvance = function(){
var that = this;
setInterval(function(){
that.attrB++;
},100);
}
element.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
Now I can do the following just fine:
var e1 = element.instance();
var e2 = element.instance();
e1.attrA = 'not e2s business';
e2.attrA = 'not e1s attrA';
The trouble starts when I try to use autoAdvance:
e1.autoAdvance();
will start the autoAdvance for all cloned 'instances' of element. I am sure this is probably rather trivial but I just don't know how to refer to the parent object inside my autoAdvance-function in a way that it gets properly cloned and only affects the instance. Thanks!
EDIT:
This is the actual code I am using:
var player = {};
player.sprites = {};
player.sprites.back = ['img/playerback_01.png','img/playerback_02.png','img/playerback_03.png'];
player.sprites.head = ['img/playerhead_01.png','img/playerhead_02.png','img/playerhead_03.png'];
player.back = new Image();
player.back.src = player.sprites.back[0];
player.head = new Image();
player.head.src = player.sprites.head[0];
player.loop = function(){
var that = this;
var loop = setInterval(function(){
//remove the [0] state from the sprite array and add it at [2]
var state = that.sprites.head.shift();
that.sprites.head.push(state);
state = that.sprites.back.shift();
that.sprites.back.push(state);
that.back.src = that.sprites.back[0];
that.head.src = that.sprites.head[0];
}, 100);
}
player.x = 0;
player.y = 0;
player.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
I generate two players:
var player1 = player.instance();
var player2 = player.instance();
But what is happening is that when I use:
player1.loop();
The animation for player2 will start to play as well.
I suggest you start using "class" in JavaScript. They are more or less a function.
function Player(){
this.sprites={};
......
}
Player.prototype.loop=function(){
....
}
var player1=new Player();
var player2=new Player();
player1.loop();
player2.loop();// this should work better
It doesn't really answer your question but it's an alternative way to write code in a cleaner and better way.

Categories