html代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>坦克大战</title>
<script src="tank.js"></script>
</head>
<body onkeydown="moveTank(hero)">
<canvas id="canvas" width="" height="" style="border:1px solid red; display:block; margin: 50px auto; background-color:black;"></canvas> <script type="text/javascript"> var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var hero = new Tank(, , , ); //创建hero对象
var hero = new Tank(, , , ); function moveTank(tank) {
//上下左右移动坦克
switch (event.keyCode) {
case ://左
tank.direct = ;
tank.moveLeft();
break;
case ://右
tank.direct = ;
tank.moveRight();
break;
case ://上
tank.direct = ;
tank.moveUp();
break;
case ://下
tank.direct = ;
tank.moveDown();
break;
default:
}
drawTank(hero);
} drawTank(hero);
</script>
</body>
</html>
JavaScript代码:
function Tank(x, y, direct, speed) {
//创建坦克类,横纵坐标,方向,速度
this.x = x;
this.y = y;
this.direct = direct;
this.speed = speed;
this.moveUp = function () {
this.y -= this.speed;
}
this.moveDown = function () {
this.y += this.speed;
}
this.moveLeft = function () {
this.x -= this.speed;
}
this.moveRight = function () {
this.x += this.speed;
}
}
function drawTank(tank) {
//画坦克
switch (tank.direct) {
case :
case :
//向上,向下
//清屏
context.clearRect(, , canvas.width, canvas.height);
//画坦克
//画*和身体
context.beginPath();
context.fillStyle = "red";
context.fillRect(tank.x, tank.y, , );//左轮
context.fillRect(tank.x + , tank.y + , , );//身体
context.fillRect(tank.x + , tank.y, , );//右轮
context.fill();
context.closePath();
//画脑袋
context.beginPath();
context.fillStyle = "blue";
context.arc(tank.x + , tank.y + , , , * Math.PI);
context.fill();
context.closePath();
//画炮筒
context.beginPath();
context.strokeStyle = "yellow";
context.lineWidth = ;
context.moveTo(tank.x + , tank.y + );
if (tank.direct == ) {
context.lineTo(tank.x + , tank.y);
} else if (tank.direct == ) {
context.lineTo(tank.x + , tank.y + );
}
context.stroke();
context.fill();
context.closePath();
break;
case :
case :
//向左,向右
//清屏
context.clearRect(, , canvas.width, canvas.height);
//画坦克
//画*和身体
context.beginPath();
context.fillStyle = "red";
context.fillRect(tank.x, tank.y, , );//左轮
context.fillRect(tank.x + , tank.y + , , );//身体
context.fillRect(tank.x, tank.y + , , );//右轮
context.fill();
context.closePath();
//画脑袋
context.beginPath();
context.fillStyle = "blue";
context.arc(tank.x + , tank.y + , , , * Math.PI);
context.fill();
context.closePath();
//画炮筒
context.beginPath();
context.strokeStyle = "yellow";
context.lineWidth = ;
context.moveTo(tank.x + , tank.y + );
if (tank.direct == ) {
context.lineTo(tank.x + , tank.y + );
} else if (tank.direct == ) {
context.lineTo(tank.x, tank.y + );
}
context.stroke();
context.fill();
context.closePath();
break;
default:
}
}