Copy link to clipboard
Copied
Hi - is it possible to add images from the library of Animate into an array first before loading them? I wanted to use the array indexing number to dynamically add any images that are linked with a naming/number convention in the library linkage. For example, all of the images I want to add to the stage would be linked in a particular order like: "myimage1", "myimage2", "myimage3", "myimage4" and so on. Can you create a library object in an array index? The error says the objects are undefined. Thanks in advance!
//CODE:
var imgNum= new Array();
var nextlibraryimage;
function addLibraryImages(){
var j;
for (j = 1; j < 4; j++) {
nextlibraryimage = String("lib.mylibraryimage"+j+"()");
imgNum
stage.addChild(imgNum
}
1 Correct answer
First, there is no "before loading them". Canvas documents completely preload everything before the page begins execution. So what you mean is before adding them to the stage, or before instantiating them.
Second, of course you can add images to an array. Images are just object references, and JavaScript arrays can hold a reference to anything.
Third, your problem isn't even with arrays. Your problem is that you think a string can do what you're trying to make it do here. Look at this:
nextlibraryi
...Copy link to clipboard
Copied
First, there is no "before loading them". Canvas documents completely preload everything before the page begins execution. So what you mean is before adding them to the stage, or before instantiating them.
Second, of course you can add images to an array. Images are just object references, and JavaScript arrays can hold a reference to anything.
Third, your problem isn't even with arrays. Your problem is that you think a string can do what you're trying to make it do here. Look at this:
nextlibraryimage = String("lib.mylibraryimage"+j+"()");
imgNum
If you'd open your browser dev console when running this, you'd see this code doesn't even run, because new on a string is an illegal operation (also even if this did work, there's no need to wrap String() around the whole thing). Without the new, you'd just be setting the array element to the string "lib.mylibraryimage1()". It is possible to use eval() to turn a string into an object reference, but this practice is slow, dangerous, and thus deprecated.
What you should be doing instead is:
imgNum
That's bracket notation. That's how you use a variable as part of an object reference.
Property accessors - JavaScript | MDN
Also this:
var imgNum= new Array();
Can just be this:
var imgNum= [];
It's very slightly faster, but mostly it's just less verbose.
Copy link to clipboard
Copied
THANK YOU! This worked beautifully! I think I had tried making it a string after trial and error without doing that. Thank you so much for the quick and informative reply! I am just getting into Animate Canvas, and I wasn't quite sure how the library is tied in. Very helpful!

