上面两张为素材图
方法一:类的方法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html{
height: 100%;
}
body{
margin: 0;
padding: 0;
height:100%;
background: url(img/bg.jpg) no-repeat;
background-size: cover;
}
img{
/*display: block;*/
position: absolute;
width: 20px;
height:auto;
}
</style>
</head>
<body>
<!--<img src="img/1.jpg"/>-->
<script src="js/startMove.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//面向对象 类的创建方法
class Fireworm{
constructor(){
this.oImg = document.createElement("img");
this.oImg.src = "img/1.jpg";
}
//取随机位置
pos(){
var cw = document.documentElement.clientWidth;
var ch = document.documentElement.clientHeight;
this.posx = Math.floor(Math.random()*(cw - 20));
this.posy = Math.floor(Math.random()*(ch - 20));
}
//萤火虫显示
show(){
//调用位置
this.pos();
document.body.appendChild(this.oImg);
this.oImg.style.left = this.posx + "px";
this.oImg.style.top = this.posy + "px";
}
//萤火虫飞
fly(){
//再去获取下位置,保证和当前位置不一样
this.pos();
//调用startMove函数来控制萤火虫的运动
startMove(this.oImg,{left:this.posx,top:this.posy},()=>{
this.fly();
})
}
}
for(let i = 0;i < 50;i++){//控制萤火虫的个数
var fireworm = new Fireworm();
fireworm.show();
fireworm.fly();
}
</script>
</body>
</html>
方法二:组合创建法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html{
height: 100%;
}
body{
margin: 0;
padding: 0;
height:100%;
background: url(img/bg.jpg) no-repeat;
background-size: cover;
}
img{
/*display: block;*/
position: absolute;
width: 20px;
height:auto;
}
</style>
</head>
<body>
<script src="js/startMove.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//面向对象 组合创建法
function Fireworm(){
this.oImg = document.createElement("img");
this.oImg.src = "img/1.jpg";
}
//获取随机位置
Fireworm.prototype.getranPos = function(){
//获取可视区域宽高
var cw = document.documentElement.clientWidth;
var ch = document.documentElement.clientHeight;
//获取萤火虫的出现位置
this.posx = Math.floor(Math.random()*(cw - 20));
this.posy = Math.floor(Math.random()*(ch - 20));
}
//萤火虫展示出来
Fireworm.prototype.show = function(){
//展示出第一次的位置
this.getranPos();
document.body.appendChild(this.oImg)
this.oImg.style.left = this.posx + "px";
this.oImg.style.top = this.posy + "px";
}
//萤火虫飞
Fireworm.prototype.fly = function(){
//再获取下位置,保证两次位置不一样
this.getranPos();
//调用运动函数startMove
startMove(this.oImg,{left:this.posx,top:this.posy},()=>{
this.fly();
})
}
for(var i = 0;i < 30;i++){//控制萤火虫的个数
var fireworm = new Fireworm();
fireworm.show();
fireworm.fly();
}
</script>
</body>
</html>