Create a Texture with Canvas2D

If you need to create textures at runtime to paint on dynamically, you may want to make use of CanvasRenderingContext2D, which is the Browsers set of 2D drawing methods on the <canvas> element.

In Wonderland Engine, you can create a texture from a canvas by simply passing it to the Texture constructor.

Example 

Below, you will find the example from the CanvasRenderingContext2D MDN page integrated in Wonderland Engine:

 1import {Component, Property, Texture} from '@wonderlandengine/api';
 2
 3export class MyCanvasTexture extends Component {
 4    static TypeName = 'my-canvas-texture';
 5    static Properties = {
 6        /* Set this material in the editor. The texture gets to applied to
 7         * all objects using it. */
 8        material: Property.material()
 9    };
10
11    start() {
12        const canvas = document.createElement('canvas');
13        canvas.width = 300;
14        canvas.height = 300;
15
16        const ctx = canvas.getContext('2d');
17        /* Do your 2D drawing here (this is the example from MDN) */
18
19        // White background fill
20        ctx.beginPath();
21        ctx.fillStyle = '#fff';
22        ctx.fillRect(0, 0, canvas.width, canvas.height);
23
24        // Change fill color back to black
25        ctx.fillStyle = '#000';
26        // Set line width
27        ctx.lineWidth = 10;
28
29        // Wall
30        ctx.strokeRect(75, 140, 150, 110);
31
32        // Door
33        ctx.fillRect(130, 190, 40, 60);
34
35        // Roof
36        ctx.beginPath();
37        ctx.moveTo(50, 140);
38        ctx.lineTo(150, 60);
39        ctx.lineTo(250, 140);
40        ctx.closePath();
41        ctx.stroke();
42
43        /* Now wrap the canvas into a Wonderland Engine texture */
44        this.canvasTexture = new Texture(this.engine, canvas);
45        /* Apply the texture to the material */
46        this.material.diffuseTexture = this.canvasTexture;
47    }
48}

Updating after Change 

After you changed a canvas after creating the initial texture, make sure to update the texture to reflect the changes.

For the above example, you would:

1    this.canvasTexture.update();

Provide additional parameters to Texture.update() to update only a subrange for better performance.