Drawing Program in Phaser

Hello.
I am trying to figure out how to add a drawing mechanic to my game. I want to be able to have the user draw what they would like with the mouse, and then be able to display what they’ve drawn in a different scene at a different time.

What is the best way to do this? Preferably I would like to store this data in JSON/something like it.

What I’ve tried:
Using graphics, which I could make work but I really want JSON support.

I think something like this should work.

var graphics1;
// Draw …

var str = JSON.stringify(
  Phaser.Utils.Objects.Pick(graphics1, [
    'commandBuffer',
    'defaultFillColor',
    'defaultFillAlpha',
    'defaultStrokeWidth',
    'defaultStrokeColor',
    'defaultStrokeAlpha',
  ])
);

var data = JSON.parse(str);

var graphics2 = this.add.graphics();

Object.assign(graphics2, data);

data = null;

I ended up just using the HTML5 Canvas element, but this looks like it will work so I will mark as solution. For reference, here is roughly what I did (in pseudocode):

add dom canvas element with id "draw"
add in a draw system (look it up, many ways to do it)
to store, just use document.getElementById("draw").getImageData(x,y,w,h) and put in JSON or something similar

Sorry if the above psuedocode above is confusing.

Canvas is a better choice I agree. Here is a 3rd party Canvas plugin, it also provides

  • Get image content via data URL (var dataURL = canvas.getDataURL())
  • Set image content via data URL (canvas.loadFromURL(dataURL))

Here is a demo of drawing on canvas, restore content of image.

  • Drag on canvas to draw dots
  • Each pointer-up will store current content of image
  • Press ‘Undo’/‘Redo’ to restore canvas