效果
编写外部框架
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width:620px;
height:450px;
position:absolute;
margin:0 auto;
left:0;
top:20px;
right:0;
bottom:0;
background:gray;
border-radius:10px;
}
#snakeDiv{
width:600px;
height:400px;
position:absolute;
margin:0 auto;
left:0;
top:10px;
right:0;
bottom:0;
}
.bottom{
width:600px;
height:30px;
position:absolute;
bottom:1px;
right:1px;
}
.bottom .button1{
position: absolute;
right: 90px;
width: 50px;
font-size: 14px;
}
.bottom .button2{
position: absolute;
right: 30px;
width: 50px;
font-size: 14px;
}
.bottom .span1{
position: absolute;
left: 10px;
color: white;
}
.bottom .span2{
position: absolute;
left: 200px;
color: white;
}
</style>
</head>
<body>
<div id='box'>
<div id='snakeDiv'>
</div>
<div class='bottom'>
<span id='score' class='span1'>分数:0</span>
<span id='time' class='span2'>时间:0</span>
<button onclick='start()' class='button1'>开始</button>
<button onclick='stop()' class='button2'>结束</button>
</div>
</div>
<script type="text/javascript" src='snake.js'></script>
</body>
</html>
效果:
添加内部画布,以及绘制地图
首先创建线的构造函数Line
function Line(ctx,o){
this.x=0,//x坐标
this.y=0,//y坐标
this.startX=0,//开始点x位置
this.startY=0, //开始点y位置
this.endX=0,//结束点x位置
this.endY=0;//结束点y位置
this.thin=false;//设置变细系数
this.ctx=ctx;
this.init(o);
}
Line.prototype.init=function(o){
for(var key in o){
this[key]=o[key];
}
}
Line.prototype.render=function(){
innerRender(this);
function innerRender(obj){
var ctx=obj.ctx;
ctx.save()
ctx.beginPath();
ctx.translate(obj.x,obj.y);
if(obj.thin){
ctx.translate(0.5,0.5);
}
if(obj.lineWidth){//设定线宽
ctx.lineWidth=obj.lineWidth;
}
if(obj.strokeStyle){
ctx.strokeStyle=obj.strokeStyle;
}
//划线
ctx.moveTo(obj.startX, obj.startY);
ctx.lineTo(obj.endX, obj.endY);
ctx.stroke();