簡體   English   中英

我在將 function 添加到數組時遇到問題。 (JavaScript)

[英]I have an issue with adding a function to an array. (JavaScript)

這是將 Function (Canvas Drawing) 添加到 sameTree 數組的代碼

let TreesI = 5;
    let sameTree = [];
    let randomValueX = mathR(-20, 20);
    let randomValueY = mathR(-20, 20);
    for (let i = 0; i < TreesI; i++) {
      randomValueX = mathR(-20, 20);
      randomValueY = mathR(-20, 20);
      sameTree[TreesI] = Tree7(randomValueX, randomValueY)
    }

但它什么也沒做,

console.log output 給出了這個

[5: 未定義] (6) = $2

這是 Tree7 的示例

function Tree7(startWidth, startHeight) {

  ctx.save();
  let treeObj = {
    translateValues: {
      startWidth: startWidth,
      startHeight: startHeight,
      endWidth: -startWidth,
      endHeight: -startHeight
    },
    scaleR: mathR(0.8, 1)
  }

  ctx.translate(treeObj.translateValues.startWidth, treeObj.translateValues.startHeight);
ctx.scale(treeObj.scaleR,treeObj.scaleR);

//ctx.strokeStyle = 'rgb(0, 100, 1)';
ctx.strokeStyle = 'black';
ctx.globalAlpha = 0.5;
ctx.lineWidth = 0.2;
var reduce = 2;
  //Tree drawing sample under
  ctx.beginPath();
  ctx.moveTo(0,0);
  ctx.lineTo(mathR(0,10),0);
  ctx.stroke();
  // Tree drawing sample above

  ctx.translate(treeObj.translateValues.endWidth, treeObj.translateValues.endHeight);
  ctx.restore();
}

現在得到一些答案后,我意識到我需要停止更新隨機值ctx.lineTo(mathR(0,10),0); . 我目前的代碼只保留坐標。 請幫忙。

如果你寫的是sameTree[i]而不是sameTree[TreesI],它將在Tree7(randomValueX, randomValueY)返回function時工作。

試試這個來存儲隨機生成的 position 值並繪制。

let TreesI = 5;
let sameTree = [];
let randomValueX = mathR(-20, 20);
let randomValueY = mathR(-20, 20);
for (let i = 0; i < TreesI; i++) {
   randomValueX = mathR(-20, 20);
   randomValueY = mathR(-20, 20);
   sameTree[i] = {"x":randomValueX, "y":randomValueY};
   Tree7(sameTree[i].x, sameTree[i].y);
}

當您想在此之后使用預生成的值進行繪制時,

for (let i = 0; i < TreesI; i++) {
   Tree7(sameTree[i].x, sameTree[i].y);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM