core-egret.sys.globalFunction

egret.sys.globalFunction 使用範例


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 給你最乾淨的程式碼, 從這行以下開始寫喔 ---

        // 背景設置
        const bgRect = new eui.Rect;
        bgRect.percentWidth = 100;
        bgRect.percentHeight = 100;
        bgRect.fillColor = 0x333333;
        this.addChild(bgRect);

        // 將色塊加入場景,其實可以用 eui.Rect,但是這裡主要是讓大家知道如何操作 canvas 轉成 bitmapdata 的範例
        const bmp = await this.createColorRectBitmap(100, 100, 0xFFCC00, 1);
        this.addChild(bmp);
    }

    public createColorRectBitmap(width: number, height: number, color: number = 0xffffff, alpha: number = 1) {
        return new Promise<egret.Bitmap>(resolve => {
            // 建立 canvas, 如果對 canvas 熟悉,可以這邊進行自己的 canvas 繪製設計
            let canvas: HTMLCanvasElement = egret.sys.createCanvas(width, height);
            // 取得 2d 內容
            let context: CanvasRenderingContext2D = canvas.getContext('2d');
            // 設置填充顏色
            context.fillStyle = `rgb(${color >> 16},${(color >> 8) & 0xff},${color & 0xff},${alpha})`;
            // 繪製矩形
            context.fillRect(0, 0, width, height);
            // egret.BitmapData.create 範例, toDataURL().split(',')[1] 是取得 base64 image 後面字段
            egret.BitmapData.create('base64', canvas.toDataURL().split(',')[1], (bmp_data) => {
                // 設置材質
                let texture = new egret.Texture();
                texture.bitmapData = bmp_data;
                // 包裝至顯示容器
                let bmp = new egret.Bitmap(texture);
                resolve(bmp);
            })
        });
    }

}

spacer

沒有留言:

張貼留言