Sample of HTML 5 game development

来源:互联网 发布:mysql 数据库备份语句 编辑:程序博客网 时间:2024/05/18 03:53

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:


原创粉丝点击