简体   繁体   English

如何循环通过 function 随机次数?

[英]How can I loop through the function random amount of times?

I'm trying to create a random amount of squares on canvas each time I press the button and then I want them to move up.每次按下按钮时,我都会尝试在 canvas 上创建随机数量的正方形,然后我希望它们向上移动。 Right now it completely ignores the for loop and only generates one square instead of random amount.现在它完全忽略了 for 循环,只生成一个正方形而不是随机数。 How to solve this?如何解决这个问题?

// Spawn
var numberArray = [0, 60, 120, 180, 240, 300, 360, 420];
var posX = numberArray[Math.floor(Math.random() * numberArray.length)];
var posY = 240;

  function spawnRandomObject() {
    // Game Object
      ctx.fillStyle = '#f2a365';
      ctx.globalCompositeOperation = "destination-over";
      ctx.beginPath();
      ctx.fillRect(posX, posY, 60, 60);
      ctx.stroke();
  }


// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  for (var i=0; i<Math.floor((Math.random()*8)+1); i++){
     spawnRandomObject(i);
  }
  posY -=60;
});

Your function has no parameters:你的 function 没有参数:
function spawnRandomObject()
but when you call it you are passing one:但是当你调用它时,你正在传递一个:
spawnRandomObject(i);
Maybe that was meant to be parameter也许这本来是参数

The other thing I see is that you are correctly calling the function a random number of times,我看到的另一件事是你正确地调用了 function 随机次数,
but the function is drawing the rectangle at the same location:但 function 在同一位置绘制矩形:
ctx.fillRect(posX, posY, 60, 60);
you set the posX, posY at the beginning and they do not change.您在开始时设置了posX, posY并且它们不会改变。
So yes you do draw multiple just on top of each other所以是的,你确实在彼此之上绘制了多个

Maybe you meant to do something like this:也许你打算做这样的事情:

 function spawnRandomObject(x, y, w, h) { ctx.beginPath(); ctx.fillRect(x, y, w, h); ctx.stroke(); } var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var rand = Math.floor((Math.random() + 1) * 8) for (var i = 0; i < rand; i++) { spawnRandomObject(i*15, i*8, 10, 10); spawnRandomObject((rand-i)*8, i*6, 5, 5); }
 <canvas id="canvas"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM