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

如何在Three.js中实现无对角线的正方形网格线框平面?

解决Three.js平面线框显示对角线的问题

你当前用PlaneGeometry加wireframe: true出现对角线,是因为PlaneGeometry的每个正方形面都是由两个三角形拼接而成的,线框模式会渲染所有三角形的边,所以会多出对角线。

下面给两种可行的解决方法:

方法一:用GridHelper直接生成正方形网格(推荐)

GridHelper是Three.js官方提供的专门用于创建平面网格的工具,天生就是正方形网格,不会有对角线,代码比手动处理PlaneGeometry简单得多:

// 替换你原来的Plane相关代码
const gridHelper = new THREE.GridHelper(50, 20, 0x000000, 0x000000);
gridHelper.position.y = -3.5;
scene.add(gridHelper);

参数说明:

  • 第一个50是网格的总尺寸,和你原来的Plane一致
  • 第二个20是分段数,对应PlaneGeometry的分段参数
  • 后两个0x000000分别是主网格线和次网格线的颜色,这里都设为黑色,和你原来的效果匹配

方法二:手动修改PlaneGeometry的边(适合必须用Plane的场景)

如果一定要基于PlaneGeometry实现,需要过滤掉对角线的边。可以通过EdgesGeometry提取所有边,再筛选出横向和纵向的边,最后用LineSegments渲染:

const planeGeometry = new THREE.PlaneGeometry(50, 50, 20, 20);
// 提取所有边
const edges = new THREE.EdgesGeometry(planeGeometry);
const filteredEdges = [];
const segmentSize = 50 / 20; // 每个网格单元的尺寸

// 遍历所有边,只保留横向或纵向的边
for (let i = 0; i < edges.attributes.position.count; i += 2) {
  // 获取两个顶点的坐标
  const [x1, y1] = [edges.attributes.position.getX(i), edges.attributes.position.getY(i)];
  const [x2, y2] = [edges.attributes.position.getX(i + 1), edges.attributes.position.getY(i + 1)];
  
  // 计算顶点在网格中的行列位置
  const col1 = Math.round(x1 / segmentSize);
  const row1 = Math.round(y1 / segmentSize);
  const col2 = Math.round(x2 / segmentSize);
  const row2 = Math.round(y2 / segmentSize);
  
  // 如果是同一列(纵向边)或同一行(横向边),保留这条边
  if (col1 === col2 || row1 === row2) {
    filteredEdges.push(x1, y1, 0);
    filteredEdges.push(x2, y2, 0);
  }
}

// 创建过滤后的几何体和线条材质
const filteredGeometry = new THREE.BufferGeometry();
filteredGeometry.setAttribute('position', new THREE.Float32BufferAttribute(filteredEdges, 3));
const lineMaterial = new THREE.LineBasicMaterial({ color: 0x000000 });

// 创建线条网格并添加到场景
const planeLines = new THREE.LineSegments(filteredGeometry, lineMaterial);
planeLines.rotation.x = Math.PI / 2;
planeLines.position.y = -3.5;
scene.add(planeLines);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:00:21