Skip to main content
Participant
February 11, 2019
Question

HTML Canvas - Addchild from a string/array?

  • February 11, 2019
  • 1 reply
  • 277 views

Hi, is it possible to addChild from a variable?

My end goal is to add and remove children based on a random array number.

Here is my test code but it is obviously looking for a linkage called P in the library (needs to load libImage1):

var _root = this;

var ButtNumbers = ["1", "2", "3"];

this.blackbutton.addEventListener('click',clickLoadLmage.bind(this));

function clickLoadLmage()

{

var libImage1 = new lib.Butt1();

var libImage2 = new lib.Butt2();

var libImage3 = new lib.Butt3();

var T = ButtNumbers[0];

var P = "libImage"+T;

_root.blackbutton.addChild(P);

}

    This topic has been closed for replies.

    1 reply

    Legend
    February 11, 2019

    Yes, it is possible. No, it's not working because P is just a string. addChild() doesn't accept a string.

    This should guide you to the correct syntax:

    Property accessors - JavaScript | MDN

    Participating Frequently
    February 12, 2019

    try

    var P = this["libImage"+T];