preloadJS是没有包含在easelJS库中,使用的话去官网下载一下就好了。
使用preloadJS其实就是主要用里面的LoadQueue这个类,在这里把这个类的API简单说下。
LoadQueue这个类包含preloadJS主要接口。LoadQueue是一个加载管理类,可以用来加载单个文件或者多个文件。
构造函数
LoadQueue ( [preferXHR=true] [basePath=""] [crossOrigin=""] )
LoadQueue的构造函数有三个参数,都是可选的:
1.preferXHR 这个表明是用XHR还是用HTML标签来加载。如果是false的时候,就用标签来加载,如果不能用标签的话,就还是用XHR来加载。默认是true,也就是说默认是用XHR来加载。
事件
你可以订阅LoadQueue的以下事件
添加文件和manifest
使用loadFile方法来添加文件或者文件列表,也可以用loadManifest方法来添加要加载的manifest。每次调用这两个方法,都会自动把文件加到队列的尾部。你想加入多少文件或者manifest都可以。
queue.loadFile("filePath/file.jpg"); queue.loadFile({id:"image", src:"filePath/file.jpg"}); queue.loadManifest(["filePath/file.jpg", {id:"image",src:"filePath/file.jpg"}]); // Use an external manifest queue.loadManifest("path/to/manifest.json"); queue.loadManifest({src:"manifest.json", type:"manifest"});
下面给出一个最简单的例子
var loader=new createjs.LoadQueue(); loader.on("complete",onComplete); loader.on("error",onError); loader.on("progress",onProgress); loader.on("fileload",onFileLoad); loader.on("fileprogress",onFileProgress); loader.loadFile("images/test1.jpg"); function onComplete(e) {
console.log("complete"); } function onError(e) {
console.log("error"); } function onProgress(e) {
console.log("progress"); } function onFileLoad(e) {
console.log("fileload"); } function onFileProgress(e) {
console.log("fileprogress"); }
使用manifest文件加载资源
LoadQueue的各种方法和设置还挺多的,我觉着初学也没必要先知道这么多。我这里写了一个自认为比较实用的例子。可以用来在游戏中预先把要用到的图片等资源加载进来,到达preload的目的。
首先我定义了一个manifest.json这样一个文件,用来存储我们资源的路径和id
[ {"src": "images/test1.jpg", "id": "test1"}, {"src": "images/test2.jpg", "id": "test2"}, {"src": "images/test3.jpg", "id": "test3"}, {"src": "images/test4.jpg", "id": "test4"} ]
src表示资源的路径,id在后面用来取加载好的资源。
然后加载这个manifest文件
var manifestLoader=new createjs.LoadQueue(); manifestLoader.loadManifest("images/manifest.json");
给manifestLoader添加fileload的事件侦听,
manifestLoader.on("fileload",function(e) {
console.log(e.result); },this,true);
window.onload=init; var stage; var loader; function init() {
stage=new createjs.Stage("canvas"); var manifestLoader=new createjs.LoadQueue(); manifestLoader.on("fileload",function(e) {
loader=new createjs.LoadQueue(); loader.on("complete",onComplete); loader.on("error",onError); loader.on("progress",onProgress); loader.on("fileload",onFileLoad); loader.on("fileprogress",onFileProgress); loader.loadManifest(e.result); },this,true); manifestLoader.loadManifest("images/manifest.json"); } function onComplete(e) {
console.log("complete"); var image1=loader.getResult("test1"); var bitmap1=new createjs.Bitmap(image1); stage.addChild(bitmap1); stage.update(); } function onError(e) {
console.log("error"); } function onProgress(e) {
console.log("progress"); } function onFileLoad(e) {
console.log("fileload"); } function onFileProgress(e) {
console.log("fileprogress"); }
在loader加载完以后,用loader.getResult这个方法就可以得到相应的资源了。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/227857.html原文链接:https://javaforall.net
