DEV Community

Tony Colston
Tony Colston

Posted on

data uri textures with Phaser3

Loading textures from Phaser3 using a data uri instead of an image file.

Be clear that this does not save space. Loading from a data uri requires that the data (the image) is encoded in a way that can fit nicely into ASCII text. In this case it is encoded in Base 64 which is larger than the original file.

Loading Image elements in Javascript is asynchronous. So you must wait for the Image to be ready.

I used Scenes to handle the loading versus the usage of the texture.

You will have a LoadingScene that will load the data-uri into the TextureManager then once that is done we will move to the next GameScene that will use the textures in Sprite objects.

The tricky bit is that I am listening to the events on the TextureManager for the scene for "textureloaded" events. I keep up with the number of events I get and use that to move on to the next Scene.

How did I know that? I looked in the source for Phaser3! This is the call for addBase64

And you can see in that source once the Image is loaded two events are fired. I picked the "addtexture" event.

The source is down below for the main portion of the code

import { mystring } from "./ds.js";
import { mystring as mystring2 } from "./ds2.js";

class LoadingTexturesOnly extends Phaser.Scene {
    constructor() {
    preload() {
        let count = 0;

        // had to read phaser source to find this
        // when you get a addtexture event the texture
        // is done loading
        this.textures.on("addtexture", () => {

            // note I am checking for 2
            // this is the number of textures that I
            // expect to be loaded and it MUST MATCH
            // the number of times you call addBase64
            if (count==2) {
                // move on to the next scene

        // ask phaser3 to load the data uri
        // I am loading 2 textures this way

class GameScene extends Phaser.Scene {
    constructor() {

    create() {
        // the keys "1" and "2" were loaded
        // in the LoadingTexturesOnly scene above


function main() {
    let gameOpts = {
        width : 600,
        height : 800,
        scene : [LoadingTexturesOnly,GameScene]
    let game = new Phaser.Game(gameOpts);

window.onload = main;
Enter fullscreen mode Exit fullscreen mode

data url :
data uri scheme:
base64 encoding:
import statement:
export statement:

Top comments (0)