How to extend Phaser.Textures.CanvasTexture

Hi, currently I know how to create a new texture using

this.newCanvasTexture = this.scene.textures.createCanvas('texturename', width, height);
this.newCanvasTexture.context.fillStyle = '#FF0000';		
this.newCanvasTexture.context.fillRect(0,0 200, 200);
this.newCanvasTexture.refresh();

this.newSprite = new Phaser.GameObjects.Sprite(this, 0, 0, 'texturename');
this.add.existing(this.newSprite);

This works fine. But I am trying to create a class that extends Phaser.Textures.CanvasTexture

and then create a new sprite using this texture;

But I just getting an error and I am not sure how to create a class that extends the CanvasTexture

export class NewClass extends Phaser.Textures.CanvasTexture {
  constructor(manager, key, source, width, height) {
    super(manager, key, source, width, height);

    this.context.fillStyle = '#FF0000';		
    this.context.fillRect(0,0 200, 200);
    this.refresh();
 }

then in scene;

let newTexture = new NewClass (this.textures, 'texturename', '', width, height);

let newSprite = new Phaser.GameObjects.Sprite(this, 0, 0, 'texturename');
this.add.existing(newSprite);

It just breaks in the CanvasTexture constructor.
Saying this.canvas.getContext is not a function
Not sure what variable should I pass between key and source.

Through createCanvas you just pass the key, no source. So how can create the same this as createCanvas but using this extended CanvasClass?

Thanks

Try this 3rd party plugin: canvas game object.

source must be a canvas. See code for TextureManager#createCanvas().

Yes, thanks. I have figured it out by looking at how Phaser createCanvas does it. But should I also manually add it into the list? Without adding to the list the texture cannot be found. I just get the no texture icon.

I added this after constructed

this.list[key] = texture;
this.emit(Events.ADD, key, texture);

Without those the CanvasTexture won’t exist.

But I’m not sure if I’m doing it the right way. Is there a special function I can use to add this CanvasTexture extended class properly?

Otherwise we are adding this manually just like the createCanvas function does. I always assume Phaser has all functions needed for everything.

There’s no special function. You just have to imitate createCanvas() and addCanvas().

But you can use the texture directly without adding it to the manager:

const canvasTexture = this.textures.createCanvas(/*…*/);

this.add.image(0, 0, canvasTexture);

Generally I would say extending CanvasTexture isn’t worth the trouble, though.

Thanks, so what I did is correct then. Manually does it, the same was createCanvas and addCanvas do.