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

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

Languages: HTML5, JavaScript

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

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();
}
最后的运行效果如下:

博主其他系列博文推荐:

1.网络采集软件核心技术剖析系列博文索引

2.手把手教你使用FineUI开发一个b/s结构的取送货管理信息系统系列博文索引

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

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

    HTML5 Canvas Game: 玩家飞船  本系列博文翻译自以下文章 http://blog.sklambert.com/html5-canvas-game-the-player-ship/ L ...

  2. 使用HTML5开发Kinect体感游戏

    一.简介 我们要做的是怎样一款游戏? 在前不久成都TGC2016展会上,我们开发了一款<火影忍者手游>的体感游戏,主要模拟手游章节<九尾袭来 >,用户化身四代,与九尾进行对决, ...

  3. Cocos2d-x-Lua 开发一个简单的游戏(记数字步进白色块状)

    Cocos2d-x-Lua 开发一个简单的游戏(记数字步进白色块状) 本篇博客来给大家介绍怎样使用Lua这门语言来开发一个简单的小游戏-记数字踩白块. 游戏的流程是这种:在界面上生成5个数1~5字并显 ...

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

    一.前言 笔者闲来无事,某天github闲逛,看到了游戏引擎的专题,引起了自己的兴趣,于是就自己捣腾了一下Cocos2dx-JS.由于是学习,所谓纸上得来终觉浅,只是看文档看sample看demo,并 ...

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

    应用:node.js 主要步骤: 创建文件夹 创建app.js(server入口,app为自定义命名) npm init -y (快速创建一个package.json文件) 依赖包安装:nodejs- ...

  6. 从零开始手把手教你使用javascript+canvas开发一个塔防游戏01地图创建

    项目演示 项目演示地址: 体验一下 项目源码: 项目源码 代码结构 本节做完效果 游戏主页面 index.html <!DOCTYPE html PUBLIC "-//W3C//DTD ...

  7. 用Python做一个飞机大战游戏

    基于pygame的一款小游戏 这是我上半年做的一款小游戏,但是一直忘记了,现在才上传代码. github项目地址:StarMan 代码基于pygame,Python版本3.5.2运行正常. 游戏很简单 ...

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

    1. Nginx 介绍        Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,它的发音为“engine X”, 是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/S ...

  9. Step by Step: 基于MFC下的COM组件开发-Helloworld

    http://blog.csdn.net/sybifei/article/details/45008745 [这篇文章有问题, 仅供参考] http://blog.csdn.net/define_us ...

随机推荐

  1. 【SPOJ - QTREE2】树链剖分

    http://acm.hust.edu.cn/vjudge/problem/19960 题意: 有一棵N个节点的树(1<=N<=10000),N-1条边,边的编号为1~N-1,每条边有一个 ...

  2. [HNOI2015]部分题解

    Day1 T2 [HNOI2015]接水果 风见幽香非常喜欢玩一个叫做 osu!的游戏,其中她最喜欢玩的模式就是接水果.由于她已经DT FC 了The big black,  她觉得这个游戏太简单了, ...

  3. HDU 2089 不要62 (数学)

    题目链接 Problem Description 杭州人称那些傻乎乎粘嗒嗒的人为62(音:laoer). 杭州交通管理局经常会扩充一些的士车牌照,新近出来一个好消息,以后上牌照,不再含有不吉利的数字了 ...

  4. hdu 2141 Can you find it?(二分查找)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2141 题目大意:查找是否又满足条件的x值. 这里简单介绍一个小算法,二分查找. /* x^2+6*x- ...

  5. cdp协议通信并发编程基础之进程

    一 . 基于UDP的套接字 udp是无链接的所以先启动哪一段都不会报错 udp服务端 import socket server=socket.socket(socket.AF_INET,socket. ...

  6. Makefile PHONY

    case 1: Makefile clean: rm a environment_1 : There is only file a $ make clean clean a environment_2 ...

  7. AC日记——[HNOI2008]越狱 bzoj 1008

    1008 思路: 越狱情况=总情况-不越狱情况: 代码: #include <cstdio> #include <cstring> #include <iostream& ...

  8. 将datatable导出为excel的三种方式(转)

    一.使用Microsoft.Office.Interop.Excel.DLL 需要安装Office 代码如下:  2         public static bool ExportExcel(Sy ...

  9. linux进程通信之管道

    1.介绍: 1)同一主机: unix进程通信方式:无名管道,有名管道,信号 system v方式:信号量,消息队列,共享内存 2)网络通信:Socket,RPC 2.管道: 无名管道(PIPE):使用 ...

  10. Codeforces #430 Div2 D

    #430 Div2 D 题意 给出一些数,每次操作先将所有数异或一个值,再求这些数中没有出现过的最小的非负整数. 分析 对于更新操作,对于 \(x\) 所有为 \(1\) 的位给相应层添加一个标记,当 ...