Search code examples
javascriptscreenshotphaser-framework

How to take screenshot of game div in phaser


I am using this code now, but it returns a blank transparent image:

$(document).ready(function(){
    $("#t").click(function() {
        html2canvas(document.querySelector("#bracelet_maker"), 
         { onrendered: function(canvas){ 
            src = canvas.toDataURL();
            window.open(src); } });
    });
});

If I use game.canvas.toDataUrl(); it returns a black image.

This is how the game is started in #bracelet_maker div

var game = new Phaser.Game(width,height,Phaser.AUTO,"bracelte_canvas",{
    preload:preload,
    create:create,
    update:update  });

Solution

  • Using Phaser.AUTO will allow either Phaser.WEBGL or Phaser.CANVAS be used, depending upon what your browser supports.

    If you switch over to Phaser.CANVAS when creating your new Phaser.Game you should be able to use access the canvas.

    For example, within Phaser by binding off the S key:

    function create() {
        // ...
        var screenshotKey = game.input.keyboard.addKey(Phaser.Keyboard.S);
        screenshotKey.onDown.add(function () { window.open(game.canvas.toDataURL()); 
    }
    

    There's also preserveDrawingBuffer which should allow you capture from WebGL as well, but it needs to be set early on in the process.

    var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
        preload: preload, create: create, update: update
    });
    game.preserveDrawingBuffer = true;