HTML5坦克大战(1)绘制坦克

时间:2022-12-29 23:52:05

坦克尺寸如下:

HTML5坦克大战(1)绘制坦克

HTML5坦克大战(1)绘制坦克

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>坦克大战</title>
</head>
<body onkeydown="tankMove()">
<canvas id="canvas" width="" height="" style="border:1px solid red; display:block; margin:50px auto;">浏览器不支持</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//构造方法,创建一个坦克类
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;
}
}
var hero = new Tank(, , , );
function drawTank(tank) {
switch (tank.direct) {
case :
case :
//向左,向右
//清空画布
context.clearRect(, , canvas.width, canvas.height);
//开始画坦克
//上轮
context.fillStyle = "red";
context.fillRect(hero.x, hero.y, , );
context.fill();
//下轮
context.fillRect(hero.x, hero.y + , , );
context.fill();
//中间
context.fillStyle = "green";
context.fillRect(hero.x + , hero.y + , , );
context.fill();
//盖子
context.beginPath()//加个开始,不然炮筒会粘连
context.fillStyle = "blue";
context.arc(hero.x + , hero.y + , , , * Math.PI);
context.fill();
context.closePath();
//炮筒
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = "0.5";
context.moveTo(hero.x + , hero.y + );
if (tank.direct == ) {
context.lineTo(hero.x, hero.y + );
} else if (tank.direct == ) {
context.lineTo(hero.x + , hero.y + );
}
context.stroke();
context.closePath();
break;
case :
case :
//向上,向下
//清空画布
context.clearRect(, , canvas.width, canvas.height);
//开始画坦克
//左轮
context.fillStyle = "red";
context.fillRect(hero.x, hero.y, , );
context.fill();
//右轮
context.fillRect(hero.x + , hero.y, , );
context.fill();
//中间
context.fillStyle = "green";
context.fillRect(hero.x + , hero.y + , , );
context.fill();
//盖子
context.beginPath()//加个开始,不然炮筒会粘连
context.fillStyle = "blue";
context.arc(hero.x + , hero.y + , , , * Math.PI);
context.fill();
//炮筒
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = "0.5";
context.moveTo(hero.x + , hero.y + );
if (tank.direct == ) {
context.lineTo(hero.x + , hero.y);
} else if (tank.direct == ) {
context.lineTo(hero.x + , hero.y + );
}
context.stroke();
break;
default: } }
function tankMove() {
switch (event.keyCode) {
case ://左A
hero.direct = ;
hero.moveLeft();
break;//不要忘记break!
case ://右D
hero.direct = ;
hero.moveRight();
break;
case ://上W
hero.direct = ;
hero.moveUp();
break;
case ://下S
hero.direct = ;
hero.moveDown();
break;
//68 87 83
default:
}
drawTank(hero);
//alert(event.keyCode);
}
drawTank(hero);
</script>
</body>
</html>