[Phaser] 畫布截圖

如今不少在微信作推廣的 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/pngimage/jpeg 可選,默認 image/png
    • encoderOptions :圖片質量,用於有損壓縮的圖像格式,介於 0 和 1 之間

另外要注意的是,遊戲每一幀只能激活一個快照,因此若是要截圖多張圖片的時候必定要在上一次截圖完成後再調用截圖的相關方法。上面的代碼用 PromisesnapshotArea 包裹起來,避免回調地獄github

tips: 若是使用 image/png 格式保存的圖片有白邊的話,能夠使用 image/jpeg 格式,避免出現白邊npm

更多截圖相關的 API, 可自行查閱api

前端phaser公衆號
qrcode_for_gh_26cb086dfbf2_258.jpg微信

相關文章
相關標籤/搜索