Issues with Canvas texture mask

Hello!

I’m currently facing some issues with Phaser.Textures.CanvasTexture . Basicaly, I would like to create several path to create a mask within my texture and then, I would like to apply that texture to a Phaser.GameObjects.Image.

Here’s a pseudo code I made to illustrate my issue.

    // Create canvas texture
    const canvas = this.scene.textures.createCanvas('puzzlePieces', 300, 300) as Phaser.Textures.CanvasTexture
    const ctx = canvas.context

    // Draw image to the canvas texture
    const image = this.scene.textures.get(this.puzzle.getId()).getSourceImage() as HTMLImageElement
    canvas.draw(0, 0, image)

    // Mask texture into a small rectangle
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, 150, 150)
    ctx.clip()

    // Create puzzle piece with the masked texture
    const puzzlePiece = new Phaser.GameObjects.Image(this.scene, 0, 0, 'puzzlePieces')
    this.add(puzzlePiece)

Maybe I don’t use correctly the canvas.context properties such as the FillRect or Paths but at the moment, when I create a new image, the texture is not masked.

Am I missing something? The goal would be to create a Jigsaw puzzle where all of the generated image represent a piece of the puzzle.

With canvas textures, you need to assign the texture to an image game object and then create a bitmap mask from that.

const texture = this.textures.createCanvas('canvas', 256, 256);

const ctx = texture.context;

ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 12;
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.stroke();

texture.refresh();

const mask = this.add.image(400, 300, 'canvas').createBitmapMask();

this.add.image(400, 300, 'sprite').setMask(mask);

However, for shapes and paths you could use a geometry mask (graphics) instead of a canvas texture.