Step by Step 使用HTML5开发一个星际大战游戏(1)

本系列博文翻译自以下文章

http://blog.sklambert.com/html5-canvas-game-panning-a-background/

Languages: HTML5, JavaScript

Code: https://github.com/straker/galaxian-canvas-game/tree/master/part1

Part 1

最终的游戏演示界面如下:

控制:移动 –  (←↑↓→)箭头
射击 – 空格

The HTML5 Page

<!DOCTYPE html>
<html>
    <head>
        <title>Space Shooter Demo</title>
        <style>
            canvas {
                position: absolute;
                top: 0px;
                left: 0px;
                background: transparent;
            }
        </style>
    </head>
    <body onload="init()">
        <!-- The canvas for the panning background -->
        <canvas id="background" width="600" height="360">
            Your browser does not support canvas. Please try again with a different browser.
        </canvas>
        <script src="space_shooter_part_one.js"></script>
    </body>
</html>

以上代码创建了一个600宽,360高的画布。

基础

创建一个封装全部图像的js对象:

/**
 * Define an object to hold all our images for the game so images
 * are only ever created once. This type of object is known as a
 * singleton.
 */
var imageRepository = new function() {
    // Define images
    this.background = new Image();
    // Set images src
    this.background.src = "imgs/bg.png";
}
 

接下来,我们创建Drawable对象,所有以后的可以运动的物体对象都继承于它,Drawable对象包含一个空的draw方法。

/**
 * Creates the Drawable object which will be the base class for
 * all drawable objects in the game. Sets up default variables
 * that all child objects will inherit, as well as the default
 * functions.
 */
function Drawable() {
    this.init = function(x, y) {
        // Default variables
        this.x = x;
        this.y = y;
    }
    this.speed = 0;
    this.canvasWidth = 0;
    this.canvasHeight = 0;
    // Define abstract function to be implemented in child objects
    this.draw = function() {
    };
}
接下来我们创建背景Background对象,注意红色部分的代码,红色2句代码是背景移动的核心。
第一句让背景从纵坐标0开始向下移动,第二句让背景从纵坐标(0-画布)高度开始向下移动,这样就产生了背景在不断向下移动的效果。最后一句蓝色代码是将Background对象的原形设置为Drawable对象,继承Drawable中的变量和方法。
/**
 * Creates the Background object which will become a child of
 * the Drawable object. The background is drawn on the "background"
 * canvas and creates the illusion of moving by panning the image.
 */
function Background() {
    this.speed = 1; // Redefine speed of the background for panning
    // Implement abstract function
    this.draw = function() {
        // Pan background
        this.y += this.speed;
        this.context.drawImage(imageRepository.background, this.x, this.y);
        // Draw another image at the top edge of the first image
        this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight);
        // If the image scrolled off the screen, reset
        if (this.y >= this.canvasHeight)
            this.y = 0;
    };
}
// Set Background to inherit properties from Drawable
Background.prototype = new Drawable();
 

最后一步

创建Game对象,Game对象获得web页面中定义的画布,初始化背景对象Background,设置背景对象的context以及画布宽,画布高属性。

/**
 * Creates the Game object which will hold all objects and data for
 * the game.
 */
function Game() {
    /*
     * Gets canvas information and context and sets up all game
     * objects.
     * Returns true if the canvas is supported and false if it
     * is not. This is to stop the animation script from constantly
     * running on older browsers.
     */
    this.init = function() {
        // Get the canvas element
        this.bgCanvas = document.getElementById(‘background‘);
        // Test to see if canvas is supported
        if (this.bgCanvas.getContext) {
            this.bgContext = this.bgCanvas.getContext(‘2d‘);
            // Initialize objects to contain their context and canvas
            // information
            Background.prototype.context = this.bgContext;
            Background.prototype.canvasWidth = this.bgCanvas.width;
            Background.prototype.canvasHeight = this.bgCanvas.height;
            // Initialize the background object
            this.background = new Background();
            this.background.init(0,0); // Set draw point to 0,0
            return true;
        } else {
            return false;
        }
    };
    // Start the animation loop
    this.start = function() {
        animate();
    };
}

以下是动画功能的实现,其中requestAnimFrame类似一个timer,会不定期的回调 animate()函数; animate()函数中调用game.background.draw();不断的重绘背景图片的位置,以实现背景滚动的动画效果。

 
/**
 * The animation loop. Calls the requestAnimationFrame shim to
 * optimize the game loop and draws all game objects. This
 * function must be a gobal function and cannot be within an
 * object.
 */
function animate() {
    requestAnimFrame( animate );
    game.background.draw();
}
/**
 * requestAnim shim layer by Paul Irish
 * Finds the first API that works to optimize the animation loop,
 * otherwise defaults to setTimeout().
 */
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame   ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
            };
})();

最后启动程序:

/**
 * Initialize the Game and starts it.
 */
var game = new Game();
function init() {
    if(game.init())
        game.start();
}
最后的运行效果如下:
时间: 2024-07-28 23:35:59

Step by Step 使用HTML5开发一个星际大战游戏(1)的相关文章

Step by Step 使用HTML5开发一个星际大战游戏(2)

HTML5 Canvas Game: 玩家飞船 本系列博文翻译自以下文章 http://blog.sklambert.com/html5-canvas-game-the-player-ship/ Languages: HTML5, JavaScript Code: https://github.com/straker/galaxian-canvas-game/tree/master/part2 2.玩家飞船 上节,我们讲述了背景滚动的实现,本节我们来实现一下玩家飞船的移动和子弹的发射. 首先让我

使用HTML5开发Kinect体感游戏

一.简介 我们要做的是怎样一款游戏? 在前不久成都TGC2016展会上,我们开发了一款<火影忍者手游>的体感游戏,主要模拟手游章节<九尾袭来 >,用户化身四代,与九尾进行对决,吸引了大量玩家参与. 表面上看,这款游戏与其它体感体验无异,实际上,它一直运行于浏览器Chrome下,也就是说,我们只需要掌握前端相应技术,就可以开发基于Kinect的网页体感游戏. 二.实现原理 实现思路是什么? 使用H5开发基于Kinect的体感游戏,其实工作原理很简单,由Kinect采集到玩家及环境数据

使用Cocos2dx-JS开发一个飞行射击游戏

一.前言 笔者闲来无事,某天github闲逛,看到了游戏引擎的专题,引起了自己的兴趣,于是就自己捣腾了一下Cocos2dx-JS.由于是学习,所谓纸上得来终觉浅,只是看文档看sample看demo,并不会让自己有多大的提升,于是一开始就计划写一个小游戏,以作为自己完成这个阶段学习的一个标志,也算是目标导向吧.完整源码移步Github: https://github.com/RogerKang/JasonAmbitionOnline Demo: http://www.rogerkang.site:

HTML5 - 开发一个自己的websocket服务器

应用:node.js 主要步骤: 创建文件夹 创建app.js(server入口,app为自定义命名) npm init -y (快速创建一个package.json文件) 依赖包安装:nodejs-websocket (github安装讲解) npm i nodejs-websocket 依赖包在appjs中的使用 (github how to use讲解) https://github.com/sitegui/nodejs-websocket#how-to-use-it 配置完毕后启动: 命

Nginx 模块开发(1)—— 一个稍稍能说明问题模块开发 Step By Step 过程

1. Nginx 介绍 Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,它的发音为“engine X”, 是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服务器.Nginx是由俄罗斯人 Igor Sysoev为俄罗斯访问量第二的 Rambler.ru站点开发的,从2004年开始它已经在该站点运行了七八年了.Igor Sysoev在建立的项目时,使用基于BSD许可. 英文主页:http://nginx.org. Nginx以事件驱动的方式编写,所以有非常

C++开发WPF,Step by Step

示例代码 使用C++来开发WPF,主要是如何在MFC(Win32)的窗口中Host WPF的Page.下面我就做个详细的介绍. 一.创建工程, 由于MFC的Wizard会生成很多用不到的代码,所以我准备从一个空的工程开始创建一个MFC的工程. a)         打开VS2005,菜单File->New->Projects-, 左面选择Visual C++->Win32,右面选择Win32 Console Application,给工程起个名字CPlusPlus_WPF, Ok进入下一

HTML5实战教程———开发一个简单漂亮的登录页面

最近看过几个基于HTML5开发的移动一样,已经越来越流畅了,相信随着职能手机的配置越来越高性能越来越好,HTML5技术的使用在移动端应用的会越来越普及,应用越来越广泛,因此作为移动开发者,掌握这门技术自然有着强烈的紧迫感.今天就写一个小小的登录页面的demo,巩固最近的学习,也给有兴趣的朋友学习HTML5技术做个参考. 在这里您可以下载到我最后实现的登录页面的demo源码,地址:http://pan.baidu.com/s/1kU1I50b. 准备工作 1.webStorm或者其他网页开发工具.

一个html5开发工具

今天推荐一个Html5开发工具 sublimetext3 找了一个注册码 可用 —– BEGIN LICENSE —– Michael Barnes Single User License EA7E-821385 8A353C41 872A0D5C DF9B2950 AFF6F667 C458EA6D 8EA3C286 98D1D650 131A97AB AA919AEC EF20E143 B361B1E7 4C8B7F04 B085E65E 2F5F5360 8489D422 FB8FC1AA

[py]python写一个通讯录step by step V3.0

python写一个通讯录step by step V3.0 参考: http://blog.51cto.com/lovelace/1631831 更新功能: 数据库进行数据存入和读取操作 字典配合函数调用实现switch功能 其他:函数.字典.模块调用 注意问题: 1.更优美的格式化输出 2.把日期换算成年龄 3.更新操作做的更优雅 准备工作 db准备 - 创建数据库 mysql> create database txl charset utf8; Query OK, 1 row affecte