Crea una Texture con Canvas2D

Se hai bisogno di creare texture a runtime per disegnare dinamicamente, potresti voler utilizzare CanvasRenderingContext2D, che è l’insieme di metodi di disegno 2D del browser sull’elemento <canvas>.

In Wonderland Engine, crea una texture da un canvas tramite l’API TextureManager.create(): this.engine.textures.create(canvas).

Esempio 

Di seguito, troverai l’esempio dalla pagina MDN di CanvasRenderingContext2D integrato in Wonderland Engine:

import {Component, Property} from '@wonderlandengine/api';

export class MyCanvasTexture extends Component {
    static TypeName = 'my-canvas-texture';
    static Properties = {
        /* Imposta questo materiale nell'editor. La texture viene applicata a
         * tutti gli oggetti che lo utilizzano. */
        material: Property.material()
    };

    start() {
        const canvas = document.createElement('canvas');
        canvas.width = 300;
        canvas.height = 300;

        const ctx = canvas.getContext('2d');
        /* Esegui qui il tuo disegno 2D (questo è l'esempio da MDN) */

        // Riempimento di sfondo bianco
        ctx.beginPath();
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // Cambia colore di riempimento a nero
        ctx.fillStyle = '#000';
        // Imposta la larghezza della linea
        ctx.lineWidth = 10;

        // Muro
        ctx.strokeRect(75, 140, 150, 110);

        // Porta
        ctx.fillRect(130, 190, 40, 60);

        // Tetto
        ctx.beginPath();
        ctx.moveTo(50, 140);
        ctx.lineTo(150, 60);
        ctx.lineTo(250, 140);
        ctx.closePath();
        ctx.stroke();

        /* Crea una texture dal canvas tramite il TextureManager */
        this.canvasTexture = this.engine.textures.create(canvas);
        /* Applica la texture al materiale (usa il setter generato) */
        this.material.setDiffuseTexture(this.canvasTexture);
    }
}

Aggiornamento dopo Modifiche 

Dopo aver modificato un canvas dopo aver creato la texture iniziale, assicurati di aggiornare la texture per riflettere le modifiche.

Per l’esempio sopra, dovresti:

this.canvasTexture.update();

Per aggiornare solo una sottoregione per migliorare le prestazioni, usa Texture.updateSubImage() invece:

// Aggiorna una regione di 100x60 alla destinazione (0, 0) dalla sorgente (28, 4)
this.canvasTexture.updateSubImage(28, 4, 100, 60, 0, 0, canvas);