[英]I have an issue with adding a function to an array. (JavaScript)
This is the code that adds the Function (Canvas Drawing) To the sameTree array这是将 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)
}
But it didn't do anything,但它什么也没做,
The console.log output gave this console.log output 给出了这个
[5: undefined] (6) = $2
[5: 未定义] (6) = $2
This is a sample of Tree7这是 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();
}
Now after getting some answers I realised that I need to stop updating the random value ctx.lineTo(mathR(0,10),0);
现在得到一些答案后,我意识到我需要停止更新随机值
ctx.lineTo(mathR(0,10),0);
. . The code I have currently just keeps the coordinates.
我目前的代码只保留坐标。 Please help.
请帮忙。
If you are writing sameTree[i] instead of sameTree[TreesI] it will work when Tree7(randomValueX, randomValueY) returns a function.如果你写的是sameTree[i]而不是sameTree[TreesI],它将在Tree7(randomValueX, randomValueY)返回function时工作。
Try this to store the randomly generated position values and draw.试试这个来存储随机生成的 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);
}
And when you want to draw with pre-generated values after this,当您想在此之后使用预生成的值进行绘制时,
for (let i = 0; i < TreesI; i++) {
Tree7(sameTree[i].x, sameTree[i].y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.