CanvasTexture:用 Canvas 动态生成贴图
CanvasTexture 允许你把 <canvas> 的内容当作贴图使用,适合做:
- 实时标注(文字/图标/数字)
- 小地图、热力图、雷达扫描
- 在不引入图片资源的情况下生成程序化纹理
基本用法
ts
import * as THREE from "three";
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 512;
const ctx = canvas.getContext("2d")!;
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fff";
ctx.font = "48px sans-serif";
ctx.fillText("Hello Three.js", 40, 120);
const texture = new THREE.CanvasTexture(canvas);
const material = new THREE.MeshStandardMaterial({ map: texture });更新内容:记得标记 needsUpdate
当你每一帧或某个时刻改了 canvas 内容,需要:
ts
texture.needsUpdate = true;如果你每帧都 needsUpdate,会有明显性能开销。更推荐“按需更新”:只有内容变化时才更新。
小技巧
- 字体尽量使用系统字体或提前加载,避免第一次绘制时闪烁
- 纹理尺寸尽量用 2 的幂(256/512/1024),更利于 MipMap
- 作为 UI/标注时可考虑
SpriteMaterial(更像 2D Billboard)
