Cocos2d-js 開發記錄:圖片資料資源等的非同步載入

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   ar   for   

這裡說的是在需要的使用載入圖片,比如遊戲中的某個關卡的圖片,不用在遊戲一開始就載入(萬一使用者玩不到那關,豈不是很冤,流量費了那麼多),否則載入速度也慢。這種方式載入資源要用到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 開發記錄:圖片資料資源等的非同步載入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.