Using Base64 Image Data with Phaser 3

When my team set out to build our final project in the Grace Hopper program, we decided to build a game where the user could draw their own character, and then have it navigate a game environment built in Phaser 3.

We initially wanted to avoid requiring users to log in to play. We used a Javascript drawing library to allow the user the draw their character. Then, rather than deal with a database at this point, the easiest solution involved saving the drawn image as Base64 data to local storage, then pulling that in the Phaser component and using it to render the player’s new sprite.

However: at the time of writing this, there appears to only be one tutorial on using base64 data with Phaser 3, and although it may work in some scenarios, it did not work for ours. That blog post, linked to by Phaser on their site, claims that in order to use base64 data, it must be added to the Phaser environment as a texture in the create() function, rather than the preload() function.

When we tried this, we got a 431 error stating that the GET request was too long. When we tried with a much smaller image (and therefore a much, much smaller base64 string), nothing would render.

What finally worked was tweaking an approach written for Phaser 2, as follows:

preload() {

let dataURI = localStorage.getItem(‘playerDrawnCharacter’)

let data = new Image();

data.src = dataURI

this.textures.addBase64(‘playerFacingRight’, dataURI, data)

}

This adds the image via base64 data, which can then be accessed the same as any other image added in the preload() function. Then, the player sprite can be created as usual in the create() function, using this.load.image(‘player’, ‘playerFacingRight’).

This worked beautifully, and allowed us to build out the ability for a user to draw their own character, their own platforms for an infinite side-scroller, and their own game prizes to collect (like the coins in Mario).

Hopefully, this will help future users trying to use base64 image data within Phaser.

Software Engineer, Trekkie, Dog Parent. Will knit a magnificent sweater but doesn’t understand the concept of time.