Sample of HTML 5 game development

本文介绍了一个简单的HTML5游戏开发实例,展示了如何使用Canvas API进行基本的游戏制作,包括监听键盘事件来控制游戏中的车辆移动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Just a sample of HTML 5 game development.

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript">
			var VehicleGame = function() {
				var ctx;
				var goRight = false, goLeft = false, pause = false;
				var vx = 0, vy = 0, dx = 4, dy = 4;
				var init = function(id) {
					var el = document.getElementById(id);
					if (el && el.getContext) {
						ctx = el.getContext("2d");
						this.run();
						this.addListener();
					}
				}

				init.prototype = {
					clear: function() {
						ctx.fillStyle = '#c2c2c2';
						ctx.fillRect(0, 0, 600, 400);
						ctx.strokeStyle = '#333';
						ctx.strokeRect(0, 0, 600, 400);
					},
					run: function() {
						var _this = this;
						this.interval = setInterval(function () {
							_this.drawVehicle();
						}, 16)
					},
					drawVehicle: function() {
						this.clear();
						var vehicle = new Image();
						vehicle.src = 'vehicle.png';
						ctx.drawImage(vehicle, vx, vy);
						if (pause) {
							this.showInfo("Paused!!!Press spacebar to cancel it!");
						}
						if (goLeft && !pause) {
							vx -= dy;
						}
						if (goRight && !pause) {
							vx += dx;
						}
					},
					showInfo: function(message) {
						ctx.fillStyle = '#333';
						ctx.font = '24px "Calibri"';
						ctx.fillText(message, 100, 180);
					},
					addListener: function() {
						document.addEventListener('keydown', function (e) {
							if (e.keyCode == 39) {
								goRight = true;
							} else if (e.keyCode == 37) {
								goLeft = true;
							}
						}, false);
						document.addEventListener('keyup', function (e) {
							if (e.keyCode == 39) {
								goRight = false;
							} else if (e.keyCode == 37) {
								goLeft = false;
							} else if (e.keyCode == 32) {
								pause = !pause ? true : false;
							}
						}, false);
					}
				}
				return init;
			}();

			window.onload = function() {
				new VehicleGame("canvas");
			}
		</script>
	</head>
	<body>
		<canvas id="canvas" width="600" height="400">
			Your browser can not support canvas, please upgrade your browser!
		</canvas>
	</body>
</html>

Result:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值