本文转至:http://blog.csdn.net/k_shl_2011/article/details/47337857
preloadJS是没有包含在easelJS库中,使用的话去官网下载一下就好了。
使用preloadJS其实就是主要用里面的LoadQueue这个类,在这里把这个类的API简单说下。
LoadQueue这个类包含preloadJS主要接口。LoadQueue是一个加载管理类,可以用来加载单个文件或者多个文件。
构造函数
- 1
- 1
LoadQueue的构造函数有三个参数,都是可选的:
1.preferXHR 这个表明是用XHR还是用HTML标签来加载。如果是false的时候,就用标签来加载,如果不能用标签的话,就还是用XHR来加载。默认是true,也就是说默认是用XHR来加载。
2.basePath
在加载资源时的,会把basePath加载url前面。这样加载同一个目录下的文件时,可以方便一点。 但是如果url是以协议(如”http://”)或者”../”这样路径开头时,不会添加basePath。
3.crossOrgin
这个参数不再用了,被LoadItem.crossOrigin取代了,这个先不管了。
事件
你可以订阅LoadQueue的以下事件
1.complete:当所有的文件都加载完成时触发。
2.error:当队列中的任何一个文件发生错误时触发。
3.progress:整个队列的加载进度发生变化时触发。
4.fileload:每个单独的文件加载完成时触发。
5.fileprogress:单独的文件加载进度发生变化时触发。只有在用XHR加载的时候才会触发。
添加文件和manifest
使用loadFile方法来添加文件或者文件列表,也可以用loadManifest方法来添加要加载的manifest。每次调用这两个方法,都会自动把文件加到队列的尾部。你想加入多少文件或者manifest都可以。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
下面给出一个最简单的例子
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
事件触发的顺序是这样的
progress
fileprogress
progress
fileprogress
progress
fileload
complete
使用manifest文件加载资源
LoadQueue的各种方法和设置还挺多的,我觉着初学也没必要先知道这么多。我这里写了一个自认为比较实用的例子。可以用来在游戏中预先把要用到的图片等资源加载进来,到达preload的目的。
总共分为四步
1.定义外部manifest;
2.加载外部manifest;
3.根据加载进来的manifest加载资源;
4.使用加载进来的资源。
首先我定义了一个manifest.json这样一个文件,用来存储我们资源的路径和id
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
src表示资源的路径,id在后面用来取加载好的资源。
然后加载这个manifest文件
- 1
- 2
- 1
- 2
给manifestLoader添加fileload的事件侦听,
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
在e.result中就是manifest.json的内容,然后再用LoadQueue去加载这些内容。
全部代码如下
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
在loader加载完以后,用loader.getResult这个方法就可以得到相应的资源了。