if (y==0) newScrollPosition[1] = yScroll * this.scrollFactor;
24 |
areaDrawn = this.drawRepeat(canvas, newPosition, newFillArea, newScrollPosition); |
25 |
} |
26 |
} |
27 |
} |
28 |
this.drawRepeat = function(canvas, newPosition, newFillArea, newScrollPosition) |
29 |
{ |
30 |
// 找到重复绘制纹理图像的起点(左上角) |
31 |
var xOffset = Math.abs(newScrollPosition[0]) % this.image.width; |
32 |
var yOffset = Math.abs(newScrollPosition[1]) % this.image.height; |
33 |
var left = newScrollPosition[0]<0?this.image.width-xOffset:xOffset; |
34 |
var top = newScrollPosition[1]<0?this.image.height-yOffset:yOffset; |
35 |
var width = newFillArea[0] < this.image.width-left?newFillArea[0]:this.image.width-left; |
36 |
var height = newFillArea[1] < this.image.height-top?newFillArea[1]:this.image.height-top; |
37 |
// 绘制图像 |
38 |
canvas.drawImage(this.image, left, top, width, height, newPosition[0], newPosition[1], width, height); |
39 |
return [width, height]; |
40 |
} |
ApplicationManager.js
01 |
/** |
02 |
ApplicationManager用于管理应用 |
03 |
@class |
04 |
*/ |
05 |
function ApplicationManager() |
06 |
{ |
07 |
/** |
08 |
初始化对象 |
09 |
@return A 对初始化对象的引用 |
10 |
*/ |
11 |
this.startupApplicationManager = function() |
12 |
{ |
13 |
this.startupGameObject(); |
14 |
this.background3 = new RepeatingGameObject().startupRepeatingGameObject(g_back2, 0, 100, 3, 600, 320, 1); |
15 |
this.background2 = new RepeatingGameObject().startupRepeatingGameObject(g_back1, 0, 100, 2, 600, 320, 0.75); |
16 |
this.background = new RepeatingGameObject().startupRepeatingGameObject(g_back0, 0, 0, 1, 600, 320, 0.5); |
17 |
return this; |
18 |
} |
19 |
|
20 |
/** |
21 |
更新当前对象 |
22 |
@param dt 自上一帧绘制起经过的秒数 |
23 |
@param context 绘制上下文 |
24 |
@param xScroll x轴的全局滚动值 |
25 |
@param yScroll y轴的全局滚动值 |
26 |
*/ |
27 |
this.update = function(/**Number*/ dt, /**CanvasRenderingContext2D*/ context, /**Number*/ xScroll, /**Number*/ yScroll) |
28 |
{ |
29 |
g_GameObjectManager.xScroll += 50 * dt; |
30 |
} |
31 |
} |
32 |
ApplicationManager.prototype = new GameObject |
在这里,我们通过ApplicationManager创建了三个RepeatingGameObject类的实例,每个实例分别显示为一个图层,使用z(深度)和scrollFactor值来创造RepeatingGameObject 渐远和渐慢的效果。
最终结果很不错。视差滚动为画布赋予了完美的纵深感,而整个效果只多编写了一个类就实现了。
看一看视差滚动的Demo吧。http://webdemos.sourceforge.net/jsplatformer4/jsplatformer4.html