cocos creator微信小遊戲截圖
阿新 • • 發佈:2018-12-22
前言
在之前,用CocosCreator製作的遊戲,截圖功能的實現是一個比較麻煩的地方,之前的官方文件也沒有相關資料,只有論壇大神給出的一些解決方案。後來cocos更新了2.0版本,camera元件大改,截圖功能也有了官方的解決方案,詳情請見這裡。不過本文討論的不是h5或是原生平臺,以上平臺可以參考上面官方文件。
開始
微信小遊戲其實已經給開發者準備了相關的截圖api–Canvas.toTempFilePath,你們可以先進去看看文件關於各個引數的解釋。這個函式的作用是,在當前的Canvas指定一個區域(沒有引數情況下則擷取整個Canvas)來截圖,最後返回一個圖片臨時路徑。根據不同的需求來使用函式返回的路徑圖片。
需求Ⅰ 預覽所截的圖,並儲存圖片
這裡需要配合微信api的另一個函式wx.previewImage,同理可先進去看看文件怎麼解釋的。
wechat_download() { let canvas = cc.game.canvas; let rate = this.wechat_canvas.parent.width / canvas.width; let width = this.wechat_canvas.width / rate; let height = this.wechat_canvas.height / rate; canvas.toTempFilePathSync({ x: canvas.width / 2 - this.wechat_canvas.width / rate / 2, y: canvas.height / 2 - (this.wechat_canvas.height / 2 + this.wechat_canvas.y) / rate, width: width, height: height, destWidth: width, destHeight: height, success : (res)=> { wx.previewImage({ current: res.tempFilePath, urls: [res.tempFilePath] }) } }) },
上面是我呼叫的過程,其中要注意的是,不同裝置適配的時候會將canvas拉伸,所以不可以直接用我們在cocos裡的尺寸,這裡我先計算放縮的比例rate,再根據rate調整截圖位置和截圖區域大小。
需求 Ⅱ 根據截圖分享小遊戲給好友
shareFriend() { let canvas = cc.game.canvas; let rate = this.wechat_canvas.parent.width / canvas.width; let width = this.wechat_canvas.width / rate; let height = this.wechat_canvas.height / rate; canvas.toTempFilePathSync({ x: canvas.width / 2 - this.wechat_canvas.width / rate / 2, y: canvas.height / 2 - (this.wechat_canvas.height / 2 + this.wechat_canvas.y) / rate, width: width, height: height, destWidth: 500, destHeight: 400, success: (res) => { wx.shareAppMessage({ imageUrl: res.tempFilePath }) } }) },
使用方法其實和上面差不多,注意目標尺寸最好是5:4吧
總結
呼叫微信api的話截圖比較簡單,但需要注意位置的定位和canvas的轉換,還有一點,上述轉發圖片功能我測試的時候,用遊客appid是不能用的,所以需要自己去申請一個appid才能使用shareAppMessage函式。