我这里有一些带有图像的功能:
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);
}
调用该函数时,如何使它随机选择这些图像之一?
您应该将图像放入一个数组中,然后选择该数组的随机索引。
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];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句