<style type="text/css">
*{
margin:0;
padding:0;
}
#map{
width:800px;
height:600px;
position:relative;
border:1px solid #ccc;
}
</style>
<body>
<div id="map"></div>
</body>
<script type="text/javascript">
window.οnlοad=function(){
var oMap=document.getElementById("map");
function Random(){}
//在原型中添加方法:获取随机数用来表示食物的坐标
Random.prototype.getrandom=function(min,max){
return Math.floor(Math.random()*(max-min)+min);
};
window.random=new Random();
function food(width,height,color){//食物进行初始化
this.width=width;
this.height=height;
this.color=color;
}
food.prototype.show=function(map){//食物在画布中如何显示
this.element=document.createElement("div");
var oDiv=this.element;
oMap.appendChild(oDiv);
oDiv.style.width=this.width+"px";
oDiv.style.height=this.height+"px";
oDiv.style.backgroundColor=this.color;
oDiv.style.position="absolute";
fd.where(oMap);
};
food.prototype.where=function(map){
var x=random.getrandom(0,(map.offsetWidth/this.width))*this.width;
var y=random.getrandom(0,(map.offsetHeight/this.height))*this.height;
var oDiv=this.element;
oDiv.style.left=x+"px";
oDiv.style.top=y+"px";
};
var fd=new food(20,20,"red");
fd.show(oMap);
};
</script>