Javascript每秒添加四个和减去两个图像

标签 javascript html

我正在尝试创建一个网站,每秒都会有四个图像出现在页面上的随机位置,然后两个图像会消失。因此,半秒内会出现四个图像,半秒内会出现两个图像,从而使其成为一秒执行。

我试图以视觉方式表现出地球上每秒有四个人出生,两个人去世。我使用名为“sunflower.png”的单个图像来执行此操作。

我的 friend 建议我这样开始我的代码,但我无法让它正常工作。相反,我的图片会弹出一秒钟,然后图像错误图标会不断重复。我究竟做错了什么?谢谢。

<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
    .sunflower {
        width: 100px;
        height: 100px;
    }
</style>
</head>

<body>
    <div id="maincontainer">
    
    <img class="sunflower" src="images/sunflower.png" alt="Sunflower">
        
    </div>
    
<script>
    function deleteImage() {
    const imagesAlreadyOnScreen = document.getElementsByClassName("sunflower"); 
    const indexToRemove = Math.floor(Math.random() * imagesAlreadyOnScreen.length);
    imagesAlreadyOnScreen[indexToRemove].remove();
    }

    const parentElement = document.getElementById("maincontainer");

    function addImage() {
        const img = document.createElement("img");


        img.setAttribute('src', 'imageLink'); 
        
        parentElement.appendChild(img) 
    }

window.setInterval(deleteImage, 500); 
    
window.setInterval(addImage, 250);
    
    
    
</script>
</body>
</html>

最佳答案

Codepen

首先,我们需要某种网格,这样我们就不会在另一个人的图片之上显示一个人的图片。我创建了一个示例 10x10 网格,其中包含 100px x 100px 的图像。

我为 Person 对象创建了一个类,该对象将根据出生和死亡间隔创建和删除。

根据可用网格位置的数量,我初始化了一个包含 100 个元素(最大人数)的数组,范围从 0 到 99。

设置出生间隔,每500ms,有4个新的人(物体)出生。

然后,1000 毫秒后,死亡间隔开始,有 2 人死亡。

当然,这只是一个帮助您入门的示例代码。您可以完全删除网格逻辑并仅使用父元素上的随机 x、y 位置。

您还可以注释掉 CSS 变换规则以查看完整尺寸的网格。

// All the positions that the grid can hold: 0-99
const grid = [...Array(100)].map(( _, idx ) => idx);

// Get a random position (0-99) from the grid Array:
function getRandomPos(){
  return grid.splice( Math.floor( Math.random() * grid.length -1 ), 1 )[0];
}

// Get the x and y grid coordinates from the random position:
function getXYfromPos( randomPos ){
  const x = randomPos % 10;
  const y = Math.floor( randomPos / 10 );
  return { x, y }
}

// Get a random person (that will die) from the people array, which holds all currently living persons:
function getRandomPerson(){
  return people[ Math.floor( Math.random() * people.length - 1 ) ];  
}

// A URL to display random images:
const URL = [ "https://picsum.photos/id", "100/100" ];

// A counter to be incremented, so that every time a new person is created, we get a new image:
let counter = 0;

// The array that will be holding the people that are born:
const people = [];

class Person {
  
  constructor(){
    this.img = document.createElement("img");
    this.img.setAttribute( "src", `${URL[0]}/${++counter}/${URL[1]}` );
    this.randomPos = getRandomPos(); 
    const xy = getXYfromPos( this.randomPos )
    this.x = xy.x;
    this.y = xy.y;
    this.img.style.left = ( this.x * 100 )+ 'px';
    this.img.style.top = ( this.y * 100 ) + 'px';
    document.querySelector("#content").appendChild( this.img );
    people.push( this );
  }
  
  remove(){
    this.img.remove();
    grid.push(this.randomPos);
    people.splice( people.indexOf( this ), 1 );
  }

}

let birthInterval;
let deathInterval;

function start(){

birthInterval = setInterval(function(){

    new Person();
    new Person();
    new Person();
    new Person();
    // console.log( "4 people are born :)" ); 
    if ( !deathInterval ){

        deathInterval = setInterval(function(){

        const randomPerson1 = getRandomPerson();
        randomPerson1 && randomPerson1.remove();
        const randomPerson2 = getRandomPerson();
        randomPerson2 && randomPerson2.remove();
        // console.log( "2 people die :(" ); 

        }, 500  );

    }

}, 500 );

}


document.querySelector("#start").onclick = start;
document.querySelector("#stop").onclick = function(){
  clearInterval( birthInterval );
  clearInterval( deathInterval );
}
* { box-sizing: border-box; }
img {
  display: inline-block;
  position: absolute;
}
body {
  margin: 0;
  padding: 0;
  background: black;
}
#content{
  border: 1px solid white;
  margin: 0 auto;
  width: 1000px;
  height: 1000px;
  position: relative;
  top: 0;
  left: 0;
  background-image: 
    linear-gradient( 0deg, white 0%, white 1%, transparent 2%, transparent),
    linear-gradient( 90deg, white 0%, white 1%, transparent 2%, transparent);
  background-size:100px 100px;
  transform: scale(0.6) translateY(-200px);
}
<button id="start">Start</button><button id="stop">Stop</button>
<div id="content"></div>

关于Javascript每秒添加四个和减去两个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130468/

相关文章:

javascript - 在混合移动应用程序中启用拼写检查

javascript - 谷歌折线图吓坏了,以随机 Angular 绘制

javascript - jQuery 克隆表单字段消失

javascript - 如何通过 API 创建 youtube 搜索

javascript - &lt;input type ="time"step ="1"> 在 Chromium 的 .value 中不返回秒数

php - 在表中显示包含周数的数据并附加数据库 php mysql 的数据

javascript - 在浏览器中加载和显示 DOM 之前修改正文 HTML 内容

javascript - 如何使用AngularJS实现这种悬停效果?

html - Markdown 中的 Span 元素

javascript - 将 HTML5 视频元素叠加在另一个视频元素上。