使用javascript HTML5在Animate CC中随机mc

时间:2018-02-25 15:19:45

标签: javascript html5 adobe

在Animate CC Canvas项目中,我在库中有几个带有这些链接名称的mc:card1card2card3 ...并且想要随机放置一个mc舞台使用Javascript / HTML5代码。

var container, c, card; // basic stuff

function init() {
  c = createjs;
  container = new c.Container();
  stage.addChild(container);

  var m = 1; // a random number
  card = new lib.this["card" + m](); // GIVES ERROR. This is AS3 style.
  //card = new lib.card1();  // WORKS FINE!
  container.addChild(card);
  card.x = 800;
  card.y = 250;
}  

我收到错误:

  

未捕获的TypeError:无法读取未定义的属性“card1”。

请问任何想法? :)

1 个答案:

答案 0 :(得分:1)

card = new lib.this["card" + m](); // GIVES ERROR. This is AS3 style.  
// card = new lib.card1();  // WORKS FINE!

由此我有两点要明确:

  • 这是因为我们不使用this关键字作为某个对象的属性。我们在对象的方法中使用它作为参考。

    var foo = { x: 1, y: 2 };
    console.log(foo.this);      // → undefined
    console.log(foo.this["x"]); // → Type Error
    
    var bar = { x: 1, y: 2, showX: function () { return this["x"] } }
    console.log(bar.showX());   // → 1
    

    但是你可以拥有一个名为this的属性:

    var foo { this: 1, that: 2 }
    console.log(foo.this);      // → 1
    


  • 您可以使用.表示法或[]表示法(不需要this)来访问对象的属性像这样:

    var foo = { x: 1, y: 2 };
    console.log(foo.x);         // → 1
    console.log(foo["y"]);      // → 2
    

所以你需要做的是:

card = new lib["card" + m]();

以下是使用div的示例。我试图按照你的代码来保持它的相似性。 lib对象有4个构造函数card1card4作为属性,每个都生成具有特定颜色的卡片。



const createjs = {
    Container: function () {
      this.elt = document.createElement("div");
      this.elt.classList.add("container");
    }
  },
  
  Card = function () {
    this.elt = document.createElement("span");
    this.elt.classList.add("card");
  },
  
  lib = {
    card1: function () {
      this.elt = new Card().elt;
      this.elt.style.background = "lightblue";
    },
    card2: function () {
      this.elt = new Card().elt;
      this.elt.style.background = "gold";
    },
    card3: function () {
      this.elt = new Card().elt;
      this.elt.style.background = "lightgreen";
    },
    card4: function () {
      this.elt = new Card().elt;
      this.elt.style.background = "#f76";
    }
  };


function init() {
  let container = new createjs.Container().elt;
  stage.appendChild(container);

  for (let m = 1; m < 5; m++) {
    let card = new lib["card" + m]().elt;
  
    card.style.width = 80 + "px";
    card.style.height = 100 + "px";
    container.appendChild(card);
  }
}  

init();
&#13;
#stage {
  background: #e85;
  height: 500px;
  padding: 1px;
}

.container {
  margin: 60px;
  background: #fff3;
}

.card {
  display: inline-block;
  border-radius: 10px;
  width: 80px;
  height: 100px;
  margin: 1em;
}
&#13;
<div id="stage"></div>
&#13;
&#13;
&#13;

相关问题