egret.ProgressEvent 使用範例
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.onPause = () => egret.ticker.pause();
egret.lifecycle.onResume = () => egret.ticker.resume();
egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
this.runGame();
}
private async loadResource() {
let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
await RES.loadConfig('resource/default.res.json', 'resource/');
await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
await RES.loadGroup('preload', 0, loadingView);
this.stage.removeChild(loadingView);
}
private async runGame() {
await this.loadResource();
// --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---
// 補充: egret.ImageLoader 不支援 ProgressEvent, 但 egret.HttpRequest 可以
// 建立 HttpRequest 物件
const request = new egret.HttpRequest;
// 回傳類型為 ArrayBuffer 類型資料
request.responseType = egret.HttpResponseType.ARRAY_BUFFER;
// 綁定 PROGRESS 事件 (如果想看載過的圖片進度, 需要清除 chrome 圖片快取)
request.addEventListener(egret.ProgressEvent.PROGRESS, (evt) => {
console.log("progress:", evt.bytesLoaded, evt.bytesTotal);
}, this);
// 解析伺服器回傳資料並顯示圖片
request.addEventListener(egret.Event.COMPLETE, (e) => {
const request = e.currentTarget as egret.HttpRequest;
egret.BitmapData.create('arraybuffer', request.response, (bitmapData) => {
const texture = new egret.Texture();
texture.bitmapData = bitmapData;
this.addChild(new eui.Image(texture));
});
}, this);
// 向伺服器索取圖片
const lb_get = this.addChild(new eui.Label) as eui.Label;
lb_get.text = '獲得圖片';
lb_get.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
const proxy = 'https://cors-anywhere.herokuapp.com/'; // blocked by CORS policy issue fix, 有些圖片禁止跨域存取時可以這樣設定
request.open(proxy + 'https://www.earthimage.org/Home_files/bigimage.jpg', egret.HttpMethod.GET);
request.send();
}, this);
}
}
沒有留言:
張貼留言