JS小方块

/产生随机小方块/
//产生随机数
//通过产生随机数来产生随机小方块
//给小方块设置宽高
//给小方块设置top left 然后实例化对象
((function(){
function Random() {
}
Random.prototype.getRandom=function(min,max){
return parseInt(Math.random()*(max-min)+min);
}
//实例化对象
window.Random=new Random;
})());

//小方块
//创建对象
var rm=new Random()
console.log(rm.getRandom(10,50));//40步

((function(){
function Food(width,height,color,x,y){
this.width=width||20;
this.height=height||20;
this.color=color||“orange”;
this.x=x||0;
this.y=y||0;
//创建div盒子
this.element=document.createElement(“div”);
}
//设置小方块显示的效果和位置—>显示在地图上面
Food.prototype.init=function(map){
var div=this.element;
//小方块的样式
div.style.width=this.width+“px”;
div.style.height=this.height+“px”;
div.style.backgroundColor=this.color;
div.style.position=“absolute”;
map.appendChild(div);
this.render(map);
}
//把小方块放到地图上
Food.prototype.render=function(map){
this.x=rm.getRandom(0,map.offsetWidth/this.width)*this.width;
this.y=rm.getRandom(0,map.offsetHeight/this.height)*this.height;
this.element.style.left=this.x+“px”;
this.element.style.top=this.y+“px”;
}

//对象实例化
var food=new Food();
food.init(document.getElementById("map"));

})())

你可能感兴趣的:(JS小方块)