Web 图形与 3D / 系统课时
Raycaster 如何选中三维物体
Raycaster 如何选中三维物体
在 Three.js 产品展示页中,用户点击 Canvas 后,浏览器只知道指针在屏幕上的位置,并不知道对应哪一个模型零件。本课把点击位置转换成相机可用的坐标,发射射线获取最近的命中网格,再把零件标识、命中距离和空间位置显示到网页上。
学习目标
- 使用 Canvas 的实际显示区域,把指针坐标转换为标准化设备坐标(NDC)。
- 用
Raycaster命中嵌套在Group中的网格,识别最近的零件。 - 处理点击空白、窗口缩放与零件高亮,验证选中结果。
把指针坐标换成 NDC
PointerEvent.clientX/clientY 相对于浏览器视口,Raycaster.setFromCamera() 需要的却是范围为 -1 到 1 的 NDC:画布中心为 (0, 0),左上角为 (-1, 1),右下角为 (1, -1)。因此不能直接把 clientX 除以窗口宽度:Canvas 可能有边距、滚动偏移或 CSS 缩放。
先用 canvas.getBoundingClientRect() 取得画布在视口中的 left、top、width、height,再计算相对比例 、,最后得到 、。Y 轴要反向,因为浏览器向下为正,而 NDC 向上为正。
例如 Canvas 左上角为 (120, 60)、显示尺寸为 800 × 450,点击发生在 (720, 285),得到 u=0.75、v=0.5,因此 NDC 为 (0.5, 0)。这里使用的是 CSS 像素,不必再乘设备像素比 devicePixelRatio。

从交点找到零件节点
调用 raycaster.setFromCamera(ndc, camera) 后,raycaster.intersectObjects(candidates, true) 会检测候选对象及其后代,返回按距离从近到远排序的交点数组。hits[0] 是最近的相交表面;数组为空表示没有命中。不要把 scene.children 全部作为候选,否则辅助网格、地面或其他装饰物也可能被选中。
单个交点的 object 是实际参与求交的对象,通常是 Mesh,不一定是产品的顶层 Group;distance 是从射线起点到交点的距离,point 是世界空间坐标。若业务零件由多个网格组成,可将稳定的 userData.partId 写在父级 Group,命中后沿 parent 向上寻找。这比直接依赖导出模型可能重复或缺失的 name 更可靠。
做一个可点击的双零件页面
将以下内容保存为 index.html。示例使用 Three.js 0.180.0 的 ES 模块,需要浏览器支持 WebGL 2,并能访问 CDN;两块立方体模拟产品零件,不依赖外部模型文件。点击后通过 hit.object 高亮网格,通过父节点的 partId 更新网页文案。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Raycaster 零件点选</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #e9eef2; }
.stage { position: relative; width: min(840px, 96vw); aspect-ratio: 16 / 9; }
canvas { display: block; width: 100%; height: 100%; touch-action: manipulation; }
#status { position: absolute; left: 12px; top: 12px; max-width: calc(100% - 48px);
padding: 8px 12px; background: white; font: 14px/1.5 sans-serif; pointer-events: none; }
</style>
<script type="importmap">
{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}
</script>
</head>
<body>
<div class="stage">
<canvas id="view"></canvas>
<div id="status" role="status">点击任意立方体</div>
</div>
<script type="module">
import * as THREE from 'three';
const canvas = document.querySelector('#view');
const status = document.querySelector('#status');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf6f8fb);
const camera = new THREE.PerspectiveCamera(55, 16 / 9, 0.1, 50);
camera.position.set(0, 1.5, 7);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight(0xffffff, 0x667788, 2));
const light = new THREE.DirectionalLight(0xffffff, 2);
light.position.set(4, 6, 5);
scene.add(light);
const product = new THREE.Group();
scene.add(product);
const meshes = [];
for (const [id, x, color] of [
['左侧机壳', -1.4, 0x31a7a0],
['右侧机壳', 1.4, 0x638ad7]
]) {
// 业务 ID 放在父级;Raycaster 实际命中子级 Mesh
const part = new THREE.Group();
part.userData.partId = id;
part.position.x = x;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1.8, 1.8, 1.8),
new THREE.MeshStandardMaterial({ color, roughness: 0.45 })
);
part.add(mesh);
product.add(part);
meshes.push(mesh);
}
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
function render() { renderer.render(scene, camera); }
function resize() {
const rect = canvas.getBoundingClientRect();
renderer.setSize(rect.width, rect.height, false);
camera.aspect = rect.width / rect.height;
camera.updateProjectionMatrix();
render();
}
function pick(event) {
const rect = canvas.getBoundingClientRect();
// 计算画布内坐标,避免页面边距造成拾取偏移
const u = (event.clientX - rect.left) / rect.width;
const v = (event.clientY - rect.top) / rect.height;
ndc.set(u * 2 - 1, 1 - v * 2);
raycaster.setFromCamera(ndc, camera);
const hits = raycaster.intersectObjects(product.children, true);
for (const mesh of meshes) mesh.material.emissive.setHex(0);
if (hits.length === 0) {
status.textContent = '未命中任何零件';
} else {
const hit = hits[0];
hit.object.material.emissive.setHex(0x154c43);
// 沿父链找零件 ID,不把子网格误当业务零件
let node = hit.object;
while (node && !node.userData.partId) node = node.parent;
const id = node?.userData.partId ?? (hit.object.name || '未命名网格');
const point = hit.point.toArray().map(n => n.toFixed(2)).join(', ');
status.textContent = `已选中:${id};距离:${hit.distance.toFixed(2)};命中点:(${point})`;
}
render();
}
canvas.addEventListener('pointerdown', pick);
window.addEventListener('resize', resize);
resize();
</script>
</body>
</html>预期结果:页面显示左右两块立方体。点左块时提示中出现“已选中:左侧机壳”,并显示随点击位置变化的距离及世界坐标;左块出现高亮。点右块会切换高亮;点空白处显示“未命中任何零件”。距离与命中点由实际点击位置决定,不应写死。
在 index.html 所在目录启动一个本地 HTTP 服务(需要 Python 3),然后访问 http://localhost:8000/:
python3 -m http.server 8000预期结果:终端显示服务启动信息并持续监听 8000 端口;浏览器能打开上述页面。若系统占用了该端口,可换一个未使用的端口并同步修改浏览器地址。CDN 无法访问时,开发者工具 Network 面板会显示模块请求失败,需先恢复网络或改用本地已安装的 Three.js 模块。
接入真实模型时怎样排错
对于已加载的 glTF 模型,可把 gltf.scene 作为拾取根节点,使用 intersectObject(gltf.scene, true);要获取“车门”而不是“车门表面网格”,应先给相关父节点分配业务 ID,再沿 hit.object.parent 向上寻找。若模型材质共用,直接改 material.emissive 会让其他零件一起变色,需先克隆材质或使用独立的选中高亮方案。
- 命中点整体偏移:检查是否错误使用
window.innerWidth、pageX或绘制缓冲区像素;优先核对getBoundingClientRect()和clientX/clientY。有视口裁剪、分屏或旋转 CSS 变换时,还要按实际渲染视口单独换算。 - 只能点中顶层,点不中内部网格:检查是否遗漏递归参数
true;另外确认候选数组确实包含模型根节点。 - 背面点击无交点:网格射线检测默认遵循材质正面朝向;先检查法线与面朝向,确需双面命中时才将材质
side设为THREE.DoubleSide。 - 前后重叠时选错:
hits[0]始终是几何相交结果中最近的表面。需要选择被遮挡零件时,必须根据部件 ID 筛选后续交点,而不能假设 Raycaster 会理解透明度或业务优先级。
通常只在 pointerdown 时拾取即可;如果改为鼠标悬停高亮,可监听 pointermove,但应限制重复计算,并在每次修改选中状态后触发渲染。