javascript - 生成元素的随机数(雨)
问题描述
我是一名新的编程学生,我已经被指令卡住了很长一段时间。我必须创建一个由 Nyan 猫下雨的动画(在某个方向,随机旋转角度等)。我尝试了很多东西,但我不知道如何在我的屏幕上添加随机数量的猫。
我试过Math.floor(Math.random()
了,但我不知道如何把它和我的猫联系起来。
这是我的代码。它可能不是很优化,但现在我可以理解“逐步”的写作。
<body>
<button id="make_it_rain">Make it rain!</button>
<img id ="cat" src="img/cat.png">
<div id="container">
</div>
<audio id="myAudio">
<source src="audio/nyancat.ogg">
<source src="audio/nyancat.mp3">
</audio>
<script>
var btn = document.getElementById("make_it_rain");
btn.addEventListener("click", rainCat);
// Animation starts
function rainCat()
{
setTimeout(animationEnd,10000);
// Background styling
var background = document.getElementById("container");
background.style.display = "block";
document.body.appendChild(background);
var pos_background = 0;
setInterval(frameBackground, 100);
// Background moves
function frameBackground()
{
if (pos_background == -100) {
pos_background = 0;
} else {
pos_background--;
background.style.top = pos_background + "%";
background.style.left = pos_background + "%";
}
}
// Cat styling
var nyanCat = document.getElementById("cat");
nyanCat.style.display = "block";
nyanCat.style.transform = "rotate(45deg)";
document.body.appendChild(nyanCat);
// Cat variables (position, rotate, speed)
var pos_cat_left = 100;
var pos_cat_top = 0;
var rotate = Math.floor(Math.random() * 360);
setInterval(oneCat, 5);
// One cat moves
function oneCat()
{
if (pos_cat_left == 100) {
pos_cat_left = Math.floor(Math.random() * 50);
pos_cat_top = 0;
rotateCat = Math.floor(Math.random() * 360);
} else {
pos_cat_top = pos_cat_top + 0.5;
pos_cat_left = pos_cat_left + 0.5;
nyanCat.style.top = pos_cat_top + "%";
nyanCat.style.left = pos_cat_left + "%";
nyanCat.style.transform = 'rotate(' + rotate + 'deg)';
}
}
// Music plays
document.getElementById('myAudio').play();
function playAudio() { audio.play(); }
}
// Animation stops
function animationEnd() {
location.reload();
}
</script>
</body>
现在动画效果很好,但我怎样才能让我的猫随机繁殖,让很多猫同时下雨呢?
非常感谢你的帮助!
解决方案
目前,您的 DOM 中只有一张猫图片,您可能必须在循环中创建多个:
const cats = [];
for(let count = 0; count < 10; count++) {
const cat = document.createElement("img");
cat.src = "./cat.png";
cat.style.display = "block";
cat.style.transform = "rotate(45deg)";
document.body.appendChild(cat);
cats.push(cat);
}
既然你有一组猫,你还必须在每个滴答声中更新它们:
function render() {
for(const cat of cats) {
// your cat update logic from oneCat()
}
requestAnimationFrame(update); // better as a timer, as it only updates on every display rerender
}
render();
推荐阅读
- java - 在Tomcat中多次重新部署Web应用程序后如何解决Metaspace OOM?
- python - 如何从列表列表中提取单词并按长度过滤单词?
- java - “HashMap”中的“volatile”关于“modCount”
- xbox - 第一次观看视频时支持 mime 类型,但在包中其他时间不支持
- s4sdk - 使用 App-To-App SSO 向 S/4 的主体传播
- ruby-on-rails - 如何修复找不到'activesupport' (= 6.0.0.rc1) - 确实找到了:[activesupport-5.2.3] (Gem::MissingSpecVersionError)
- php - wordpress 中查看页面源“冗余空白行”时出错
- numpy - 为什么三角函数计算的结果不同?
- selenium-webdriver - 如何使用 selenium 获取链接并使用 beautifulsoup 进行抓取?
- android - 如何自动切换viewpager?