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);

            }

        })

    })

};

 

你可能感兴趣的:(cocos2d-js)