1. 程式人生 > >laya 微信小遊戲 分享 功能

laya 微信小遊戲 分享 功能

  此功能的要點同,如何取得wx, if (Laya.Browser.onMiniGame) {

this.wx = Laya.Browser.window.wx;

}

然後通過wx.createCanvas()建立一個離屏canvas.然後通過canvas.getContext('2d')取得context,再通過context畫圖,以及上面寫文字,最後通過canvas.toTempFilePathSync動態生成一個圖片,作為分享的素材.

以下是分享函式完整程式碼:

        private onShare(e: Laya.Event): void {

            if (this.wx == null) {

                this.playerControl.Relive(true);

                return;

            }

            var canvas = this.wx.createCanvas();

            canvas.width = 640;

            canvas.height = 480;

            var context = canvas.getContext('2d');

            var bgm = this.wx.createImage();

            bgm.src = 'res/Texture/Share.png';

            bgm.onload = () => {

                context.drawImage(bgm, 0, 0, 640, 480);

                context.fillStyle = "rgba(0,0,0,1)";

                context.font = "bold 30px Arial";

                context.textAlign = "left";

                context.textBaseline = "middle";

                context.fillText("米數", 200, 100);

                context.fillText(this.label_distance.text + " M", 240, 190);

                this.wx.shareAppMessage({

                    title: "我在【雲端酷跑】跑了" + this.label_distance.text + "米,敢與我比比嗎?",

                    imageUrl: canvas.toTempFilePathSync({

                        destWidth: 640,

                        destHeight: 480

                    }),

                    success: () => {

                        this.playerControl.Relive(true);

                    },

                    fail: () => {

                        this.playerControl.Relive(false);

                    }

                })

            }

        }