egret.Base64Util.encode 範例
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.crossOrigin = 'anonymous';
// await 方式, 下面 await this.getImageByURL 跑完才會執行 this.addChild(img1); 與後面的程式
const img1 = await this.getImageByURL('https://www.google.com/pathtoimg1.png');
this.addChild(img1);
// then 方式, 採 callback 方式進行
this.getImageByURL('https://www.google.com/pathtoimg2.png').then(img2 => {
this.addChild(img2);
});
}
// 取得網路圖片方法, egret.Base64Util.encode 範例
private getImageByURL(url: string) {
return new Promise<eui.Image>(resolve => {
fetch(url).then(response => response.arrayBuffer()).then(arrayBuffer => {
const base64Src = 'data:image/png;base64,' + egret.Base64Util.encode(arrayBuffer); // convert ArrayBuffer to base64 image string
resolve(new eui.Image(base64Src));
});
});
}
}
沒有留言:
張貼留言