Cocos2d-js异步图片加载

这里说的是在需要的使用加载图片,比如游戏中的某个关卡的图片,不用在游戏一开始就加载(万一用户玩不到那关,岂不是很冤,流量费了那么多),否则 载入速度也慢。这种方式加载资源要用到cc.loader官方文档上有介绍(http://www.cocos2d-x.org/docs/manual/framework/html5/v3/cc-loader/zh),主要有

  • loadJs
  • loadJsWithImg
  • loadTxt
  • loadBinary
  • loadImg
  • loadJson

文档给出了一个例子如下:

cc.loader.loadTxt("res/a.txt", function(err, data){
if(err) return console.log("load failed");
//success
});

 可见loadTxt中的第二个是一个回调函数(等待ajax数据返回后调用),文档中对启动load系列函数参数都没有说,其实都是如此,回调函数第一个 参数表示是否有错误发生(成功的话是null),第二个参数data表示本次请求返回的数据(不同load系列函数会对返回数据进行一个解析,就是解析的 结果了,比如loadImg)。其实第一次看文档的时候没看到这段示例代码,全是回调函数只有一个参数的示例代码,当时我就想啊,尼玛这异步调用数据怎么 取啊?文档也不说一声,只好去看源码,开源的好处就是这样,以下是loadBinary的代码:

/**
* Load binary data by url.
* @function
* @param {String} url
* @param {Function} [cb]
*/
cc.loader.loadBinary = function (url, cb) {
var self = this;
var xhr = this.getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
xhr.open("GET", url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "x-user-defined");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]);
cb(null, self._str2Uint8Array(fileContents));
} else cb(errInfo);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined");
xhr.onload = function () {
xhr.readyState == 4 && xhr.status == 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);
};
}
xhr.send(null);
};
cc.loader._str2Uint8Array = function (strData) {
if (!strData)
return null;
var arrData = new Uint8Array(strData.length);
for (var i = 0; i < strData.length; i++) {
arrData[i] = strData.charCodeAt(i) & 0xff;
}
return arrData;
};

 

可以看到这里对回调函数的调用:

xhr.readyState == 4 && xhr.status == 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);

再来给出一个自己的使用实例(加载游戏关卡的参数和图片):

/* helper function to fetch level data using ajax */
var fetch_level = function(level, callback, callback_data) {
cc.loader.loadJson("api/level/" + level, function (x, new_level_data) {
cc.log("fetch level json data:", new_level_data);
current_level_data = new_level_data;
cc.loader.loadImg(current_level_data.photo, function (x, img) {
cc.log("fetch level photo img:", img);
current_level_data.img = img;
if (!!callback) {
callback(callback_data);
}
})
})
};

 

 

至于如何动态加载远程图片,研究结果如下(可以用):

		var that = this;
		var url = "http://www.bookgogo.com/Public/Images/weixinini.png";
		cc.loader.loadImg(url, null, function(err,img){
			var logo  = new cc.Sprite(img);
			that.addChild(logo,10);
			logo.x = size.width / 2;
			logo.y = size.height / 2;
		});

 

posted @ 2014-11-12 13:19  recock  阅读(1205)  评论(0编辑  收藏  举报