您的位置:首页 > Web前端 > HTML5

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

2016-09-25 23:26 155 查看
坦克尺寸如下:





<!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="1000" height="500" 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(100, 60, 1, 5);
function drawTank(tank) {
switch (tank.direct) {
case 0:
case 2:
//向左,向右
//清空画布
context.clearRect(0, 0, canvas.width, canvas.height);
//开始画坦克
//上轮
context.fillStyle = "red";
context.fillRect(hero.x, hero.y, 30, 5);
context.fill();
//下轮
context.fillRect(hero.x, hero.y + 15, 30, 5);
context.fill();
//中间
context.fillStyle = "green";
context.fillRect(hero.x + 5, hero.y + 6, 20, 8);
context.fill();
//盖子
context.beginPath()//加个开始,不然炮筒会粘连
context.fillStyle = "blue";
context.arc(hero.x + 15, hero.y + 10, 3, 0, 2 * Math.PI);
context.fill();
context.closePath();
//炮筒
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = "0.5";
context.moveTo(hero.x + 15, hero.y + 10);
if (tank.direct == 0) {
context.lineTo(hero.x, hero.y + 10);
} else if (tank.direct == 2) {
context.lineTo(hero.x + 30, hero.y + 10);
}
context.stroke();
context.closePath();
break;
case 1:
case 3:
//向上,向下
//清空画布
context.clearRect(0, 0, canvas.width, canvas.height);
//开始画坦克
//左轮
context.fillStyle = "red";
context.fillRect(hero.x, hero.y, 5, 30);
context.fill();
//右轮
context.fillRect(hero.x + 15, hero.y, 5, 30);
context.fill();
//中间
context.fillStyle = "green";
context.fillRect(hero.x + 6, hero.y + 5, 8, 20);
context.fill();
//盖子
context.beginPath()//加个开始,不然炮筒会粘连
context.fillStyle = "blue";
context.arc(hero.x + 10, hero.y + 15, 3, 0, 2 * Math.PI);
context.fill();
//炮筒
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = "0.5";
context.moveTo(hero.x + 10, hero.y + 15);
if (tank.direct == 1) {
context.lineTo(hero.x + 10, hero.y);
} else if (tank.direct == 3) {
context.lineTo(hero.x + 10, hero.y + 30);
}
context.stroke();
break;
default:

}

}
function tankMove() {
switch (event.keyCode) {
case 65://左A
hero.direct = 0;
hero.moveLeft();
break;//不要忘记break!
case 68://右D
hero.direct = 2;
hero.moveRight();
break;
case 87://上W
hero.direct = 1;
hero.moveUp();
break;
case 83://下S
hero.direct = 3;
hero.moveDown();
break;
//68 87 83
default:
}
drawTank(hero);
//alert(event.keyCode);
}
drawTank(hero);
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: