1

I'm using Canvas/javascript (createjs) and am having difficulty calling an instance or adding a child to stage of a cloned shape (via an array using a for loop adding incremental numbers).

var myShape = new createjs.Shape();
myShape.graphics.f("white").rr(0, 0, 300, 300, 12);

myShape1 = myShape.clone();
myShape2 = myShape.clone();
myShape3 = myShape.clone();

//var arr = [null,cellFlasha1, cellFlasha2, cellFlasha3, cellFlasha4];

var arr = [];
for (var i = 1; i <= 4; i++) {
     arr.push(["myShape"+i]);
}

stage.addChild(arr[1]);

I can't seem to add and instance to the stage. It does work when I use the array that has been commented out though. Could it be how i've combined a string and value when I push it to the array as an object?

I know I could just add it to stage by doing stage.addChild(myShape1); etc.. but I want to do it via a loop as there as there will be many more instances to come and similar scenarios (I intend to loop how I add the clones too so the number of objects can just be defined once)

I'm relatively new to javascript so my terminology may not be great. Many thanks in advance. Any help would be much appreciated!

jimjimmer
  • 13
  • 3

2 Answers2

2

Muzaffar is correct that you can access those variables via the window object, but it is generally a code smell to rely on globals for this kind of thing. Is all you need to get an arbitrary number of those shapes into an array? If so, why not try something like this?

function cloneShapeIntoArray(shape, num) {
  var shapeArray = [];

  for (var i = 0; i <= num; i++) {
    shapeArray.push(shape.clone());
  }

  return shapeArray;
}

function addShapesToStage(shapes, stage) {
  for (var i = 0; i <= shapes.length; i++) {
    stage.addChild(shapes[i]);
  }
}

var myShape = new createjs.Shape();
myShape.graphics.f("white").rr(0, 0, 300, 300, 12);

var shapes = cloneShapeIntoArray(myShape, 3);

// You can do some extra stuff to the shapes here, eg you could make each one a different scale
// shapes[0].scale = 1
// shapes[1].scale = 1.5
// shapes[2].scale = 2

addShapesToStage(shapes, stage);

That allows you to easily control how many copies you want, and does not pollute the global namespace.

Muzaffar Mahmood
  • 1,688
  • 2
  • 17
  • 20
Chris O'Kelly
  • 1,863
  • 2
  • 18
  • 35
  • Super! thanks Chis, I will give this a go shortly. And thanks for informing me of good practices too etc. Much appreciated – jimjimmer Mar 01 '19 at 08:13
0

Yes you can do this with "window" global object. Something like this

for(var i=1; i<=4; i++) {
    window['myShape'+i] =  myShape.clone();
}
var arr = [];
for (var i=1; i<= 4; i++) {
     arr.push(window['myShape'+i]);
}

For more detail you can see here: Use dynamic variable names in JavaScript

Muzaffar Mahmood
  • 1,688
  • 2
  • 17
  • 20
  • I thought I had left a comment earlier but it doesn't seem to have been added. Thanks so much for your help, works great! – jimjimmer Mar 01 '19 at 11:12