一.创建方法:
–构造函数定义敌方小飞机
(1)属性:
[1]图片节点
[2]图片
[3]x坐标
[4]y坐标
[5]速度
(2)行为:
[1]移动
[2]初始化 把图片节点添加到mainObj里
二.代码实现:
html+css
<!--下为css部分,主要是背景图的设置-->
*{margin:0;padding:0;}
#main{width:400px;
height:600px;
background:url("../img/background_1.png");
margin:30px auto;
position:relative;
overflow:hidden;}
<!--下为div主要是背景图设置-->
<div id="main"></div>
JS部分
//下为创建一个实例模板
function SmallPlaneProto(imgSrc,x,y,speed){
this.imgNode=document.createElement('img');
this.imgSrc=imgSrc;
this.x=x;
this.y=y;
this.speed=speed;
//下为初始化效果
this.init=function(){
this.imgNode.src=this.imgSrc;
this.imgNode.style.position='absolute';
this.imgNode.style.left=this.x+'px';
this.imgNode.style.top=this.y+'px';
mainObj.appendChild(this.imgNode);
}
//初始化效果定义完成后进行函数调用
this.init();
this.move=function(){
this.imgNode.style.top=parseInt(this.imgNode.offsetTop)+this.speed+'px';
}
}
function createSmallPlane(){
var smallPlane=new SmallPlaneProto('../img/enemy1_fly_1.png',random(0,356),random(0,576),parseInt(random(1,5)))
//下为将创建的实例化对象添加到数组smallPlaneArray中
smallPlaneArray.push(smallPlane);
}
//批量创建敌方小飞机
setInterval(createSmallPlane,1000);
//为实现敌方飞机的不同位置显示,即x,y坐标为随机值
function random(min,max)
{
return parseInt(Math.random()*(max-min)+min);
}
//函数实现每一台小飞机的移动
function smallPlaneMove(){
for(i=0;i<smallPlaneArray.length;i++)
{smallPlaneArray[i].move();
//边界判断,即当小飞机离开background范围内时进行节点移除
if(parseInt(smallPlaneArray[i].imgNode.offsetTop)>=600)
{mainObj.removeChild(smallPlaneArray[i].imgNode);//移除子节点
smallPlaneArray.splice(i,1);//数组中删除数组元素
}
}
}
//让实例中的move函数进行定时执行
setInterval(smallPlaneMove,50);