You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Three.js的PlaneGeometry上批量绘制指定矩形?

解决Three.js PlaneGeometry上绘制多个矩形的问题

问题根源

  • 你的代码每次循环都会新建一个独立的Canvas,每个Canvas仅绘制一个矩形,但最终只使用了第一个Canvas的纹理,因此Plane上仅显示单个矩形。
  • 循环中ctxArr[0] = this.createStroke(j)持续覆盖数组同一位置,既没有保存多个上下文,也完全没必要使用多Canvas——所有矩形应该绘制在同一个Canvas上。

修正后的完整代码

// 创建单个Canvas并在其上绘制多个矩形
createMultiStrokeCanvas = () => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  // 必须设置Canvas尺寸,避免绘制内容被裁切或压缩
  canvas.width = 200;
  canvas.height = 50;
  
  ctx.fillStyle = "white";
  ctx.strokeStyle = "white";
  ctx.lineWidth = 2;

  // 循环绘制5个不重叠的矩形
  for (let j = 0; j < 5; j++) {
    // 调整间距参数,控制矩形之间的距离
    ctx.strokeRect(10 + j * 40, 5, 30, 30);
  }

  return canvas;
}

// 生成纹理并创建Plane
const canvas = this.createMultiStrokeCanvas();
const texture = new THREE.CanvasTexture(canvas);

const planeGeo = new THREE.PlaneGeometry(5, 6);
const planeMaterial = new THREE.MeshBasicMaterial({
  map: texture,
  transparent: true, // 可选,需要Canvas背景透明时开启
});

const plane = new THREE.Mesh(planeGeo, planeMaterial);
plane.position.set(3, 0, 0);
this.scene.add(plane);

关键注意事项

  • 务必设置Canvas的width和height属性,默认尺寸极小,会导致绘制内容被压缩或裁切。
  • 调整矩形位置的偏移参数(示例中j * 40),可控制矩形间距,避免重叠。
  • 若需要Canvas背景透明,需给材质添加transparent: true,否则Canvas默认的黑色背景会覆盖Plane。

内容的提问来源于stack exchange,提问作者Satyam Raikwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:45:47