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, create a texture from a canvas via the
TextureManager.create() API:
this.engine.textures.create(canvas).
Example
Below, you will find the example from the CanvasRenderingContext2D MDN page integrated in Wonderland Engine:
import {Component, Property} from '@wonderlandengine/api';
export class MyCanvasTexture extends Component {
static TypeName = 'my-canvas-texture';
static Properties = {
/* Set this material in the editor. The texture gets applied to
* all objects using it. */
material: Property.material()
};
start() {
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 300;
const ctx = canvas.getContext('2d');
/* Do your 2D drawing here (this is the example from MDN) */
// White background fill
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Change fill color back to black
ctx.fillStyle = '#000';
// Set line width
ctx.lineWidth = 10;
// Wall
ctx.strokeRect(75, 140, 150, 110);
// Door
ctx.fillRect(130, 190, 40, 60);
// Roof
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();
/* Create a texture from the canvas via the TextureManager */
this.canvasTexture = this.engine.textures.create(canvas);
/* Apply the texture to the material (use generated setter) */
this.material.setDiffuseTexture(this.canvasTexture);
}
} 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:
this.canvasTexture.update(); To update only a subregion for better performance, use Texture.updateSubImage() instead:
// Update a 100x60 region at destination (0, 0) from source (28, 4)
this.canvasTexture.updateSubImage(28, 4, 100, 60, 0, 0, canvas);