HTML5的出現為游戲開發提供了更多的可能性,下面是一份HTML5登山賽車的源碼,希望對開發有所幫助:
var car = { x: 150, y: 0, speed: 0, acceleration: 0.1, image: null, width: 0, height: 0, init: function() { this.image = new Image(); this.image.src = 'car.png'; this.width = this.image.width; this.height = this.image.height; }, move: function() { if (keys[37]) { // left arrow this.speed -= this.acceleration; } else if (keys[39]) { // right arrow this.speed += this.acceleration; } else { this.speed *= 0.9; } this.x += this.speed; if (this.x< 0) { this.x = 0; this.speed = 0; } else if (this.x + this.width >canvas.width) { this.x = canvas.width - this.width; this.speed = 0; } }, draw: function(context) { context.drawImage(this.image, this.x, this.y); } }; var keys = {}; window.addEventListener('keydown', function(e) { keys[e.keyCode] = true; }, false); window.addEventListener('keyup', function(e) { keys[e.keyCode] = false; }, false); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var score = 0; var intervalId = setInterval(function() { // draw background context.fillStyle = 'rgb(200, 200, 200)'; context.fillRect(0, 0, canvas.width, canvas.height); // update car position car.move(); // draw car car.draw(context); // update score score += 1; // display score context.font = '20px Arial'; context.fillStyle = 'rgb(0, 0, 0)'; context.fillText('Score: ' + score, 10, 20); }, 30); car.init();
以上是HTML5登山賽車的源碼,其中包括了小車的移動、鍵盤控制、得分統計等基本功能。HTML5為游戲開發提供了更多的可能性,我們可以使用javascript來控制游戲的行為,使用canvas來繪制游戲界面,希望這個簡單的例子能夠對開發者有所幫助。
上一篇html5留言板代碼下載
下一篇php怎么設置css樣式