使用 Canvas2D 创建纹理

如果您需要在运行时创建纹理以进行动态绘制,可以使用 CanvasRenderingContext2D, 这是浏览器为 <canvas> 元素提供的一系列2D绘图方法。

在 Wonderland Engine 中,可以通过 TextureManager.create() API 从 canvas 创建一个纹理:this.engine.textures.create(canvas)

示例 

下面是从 CanvasRenderingContext2D MDN 页面整合到 Wonderland Engine 的示例:

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

export class MyCanvasTexture extends Component {
    static TypeName = 'my-canvas-texture';
    static Properties = {
        /* 在编辑器中设置此材质。纹理会应用到使用它的所有对象上。*/
        material: Property.material()
    };

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

        const ctx = canvas.getContext('2d');
        /* 在这里进行您的2D绘图(这是来自MDN的示例) */

        // 填充白色背景
        ctx.beginPath();
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 将填充颜色改回黑色
        ctx.fillStyle = '#000';
        // 设置线宽
        ctx.lineWidth = 10;

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

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

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

        /* 通过 TextureManager 从 canvas 创建纹理 */
        this.canvasTexture = this.engine.textures.create(canvas);
        /* 将纹理应用到材质上(使用生成的setter) */
        this.material.setDiffuseTexture(this.canvasTexture);
    }
}

更改后更新 

在您创建初始纹理后更改了 canvas,确保更新纹理以反映更改。

对于上述示例,您需要执行以下操作:

this.canvasTexture.update();

为了提高性能,仅更新子区域,请使用 Texture.updateSubImage()

// 更新目标 (0, 0) 的100x60区域,从源 (28, 4) 处开始
this.canvasTexture.updateSubImage(28, 4, 100, 60, 0, 0, canvas);