Set position of snapshot in Phaser 3

Viewed 463

I'm using this Phaser 3 example and I need to display the snapshot in a predefined position. Currently every snapshot gets displayed below the body with document.body.appendChild(image);

I tried this.add.sprite(0, 0, image).setOrigin(0.5,0); but it returns an error:

Uncaught TypeError: Cannot read property 'add' of null

Code:

  this.input.on('pointerdown', function (pointer) {

    var textureManager = this.textures;

    this.game.renderer.snapshotArea(pointer.x, pointer.y, 128, 128, function (image)
    {
        document.body.appendChild(image);

        if (textureManager.exists('area'))
        {
            textureManager.remove('area');
        }

        textureManager.addImage('area', image);

        particles.setTexture('area');
    });

}, this);
1 Answers

I left the part that appended images at the end of the body in but feel free to edit as needed.

var snapshot
var lastpointer = {x: 100, y: 100} 
this.input.on('pointerdown', (pointer) => {
    var textureManager = this.textures;
    this.game.renderer.snapshotArea(pointer.x, pointer.y, 128, 128, (image) => {
        lastpointer.x = pointer.x
        lastpointer.y = pointer.y
        document.body.appendChild(image);
       
        if (textureManager.exists('area'))
        {
            textureManager.remove('area');
        }

        textureManager.addImage('area', image);

        particles.setTexture('area');

        // Add the snapshot to the texture cache
        if (textureManager.exists('snapshot'))
        {
            textureManager.remove('snapshot');
            snapshot.destroy();
            snapshot = null;
        }
        textureManager.addBase64('snapshot', image.src);
    });

}, this);

// When the snapshot is actually loaded, add it to the pointer coordinates (or simply fixed ones)
this.textures.on('addtexture', function (texture) {
    if('snapshot' === texture) {
        snapshot = this.add.image(lastpointer.x, lastpointer.y, 'snapshot');
    }
}, this);
Related