如今不少在微信作推廣的 h5 常常須要用到長按保存活動圖片的功能,Phaser 就有這樣一個 api 能夠直接用來截圖保存html
<!DOCTYPE html> <html> <head> <!-- 引入 phaser --> <script src="https://cdn.jsdelivr.net/npm/phaser@3.15.1/dist/phaser-arcade-physics.min.js"></script> </head> <body> <div id="game" class="game"></div> <div class="snapshot"></div> <script> let PlayGame = new Phaser.Class({ Extends: Phaser.Scene, initialize: function PlayGame() { Phaser.Scene.call(this, { key: 'playGame', active: false }) }, preload() { this.load.image('bg', 'bg.jpg') }, snapshot() { return new Promise((resolve) => { // 主要就是這句代碼 this.game.renderer.snapshotArea(0, 0, 750, 1464, (image) => { $('.snapshot').append(image) resolve() }, 'image/jpeg') }) }, create() { this.add.image(game.config.width / 2, game.config.height / 2, 'bg') this.snapshot() } }) let config = { type: Phaser.AUTO, parent: 'game', width: 750, height: 1464, transparent: false, backgroundColor: '#000000', scene: PlayGame } let game = new Phaser.Game(config) </script> </body> </html>
上面的核心代碼是 snapshotArea
方法,使用這個方法就能夠實現對畫布的截圖。前端
snapshotArea(x, y, width, height, callback[, type][, encoderOptions])
git
x, y
:截圖的起始座標width, height
:截圖的寬高callback
:截圖後的回調方法type
:圖像格式,有 image/png
和 image/jpeg
可選,默認 image/png
encoderOptions
:圖片質量,用於有損壓縮的圖像格式,介於 0 和 1 之間另外要注意的是,遊戲每一幀只能激活一個快照,因此若是要截圖多張圖片的時候必定要在上一次截圖完成後再調用截圖的相關方法。上面的代碼用 Promise
把 snapshotArea
包裹起來,避免回調地獄github
tips: 若是使用 image/png
格式保存的圖片有白邊的話,能夠使用 image/jpeg
格式,避免出現白邊npm
前端phaser公衆號微信