简体   繁体   English

我如何在 function 中随机制作一些东西?

[英]How do i make something random in a function?

I have a function with some images in it here:我有一个 function,里面有一些图片:

function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}

How do I make this function randomly choose one of these images when I call it?当我调用它时,如何让这个 function 随机选择这些图像之一?

You should put your images in an array, then pick a random index of the array.您应该将图像放入数组中,然后选择数组的随机索引。

function randomImage() {
  const images = [
    image1,
    image2,
    image3,
    image4,
  ];
  // Pick an index at random from the images array. Math.rand returns
  // a random number between 0 and 1, multiplying that by the length
  // of the images array, gets a number between 0 and the length of the
  // array, and flooring it makes it into an integer.
  const randomIndex = Math.floor(Math.rand() * images.length);
  return images[randomIndex];
}

I think it's inconvenient to do math when I want to deal with randomness, so I use Rando.js to make stuff like this simple and readable.当我想处理随机性时,我认为做数学很不方便,所以我使用Rando.js来制作这样简单易读的东西。

 var images = ["one", "two", "three", "four"]; console.log( rando(images).value );
 <script src="https://randojs.com/1.0.0.js"></script>

If you want to use this code, all you need to know is that the script tag sources in the rando function, and you're ready to use it right away.如果你想使用这段代码,你只需要知道rando function中的script标签来源,你就可以马上使用了。 Just put the script tag in the head of your HTML document.只需将脚本标签放在 HTML 文档的头部即可。 It's easy, but if you need to know more, you can check out examples on the website or github repo .这很简单,但如果您需要了解更多信息,可以查看网站github repo上的示例。

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

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