Copy canvas sometimes black

Hello, I’m trying to copy the canvas to collect data. It’s fairly straight forward code.

captureCanvas() {
    var img = new Image;

    img.onload = () => {
      var mc = document.getElementById('machine-canvas');
      var context = mc.getContext('2d');
      var scale = this.scaleImage(img.width, img.height, 224, 224, false); //math
      
      context.drawImage(
        img,
        scale.targetleft,
        scale.targettop,
        scale.width,
        scale.height
      );
    }

    var holder = document.querySelector('canvas').toDataURL();
    img.src = holder;
  }

Sometimes the canvas is black though, other times it works as expected. It seems to only work when the secondary canvas is visible and Phaser one is hidden. Does anyone know how to solve the black screen with canvas copy?

Hi @EddieOne, do not take the image from the Phaser’s canvas context directly, as Phaser may be in the middle of screen refresh when you do so. It may cause a black screen error. What I would suggest is using Phaser’s snapshot method.

This example could be helpful for your use case: http://labs.phaser.io/view.html?src=src\snapshot\snapshot%20game.js

4 Likes

Hello Survesh, thank you for the info. game.renderer.snapshot will be perfect.

1 Like