Atlaslog
Atlaslog / Examples / three.js / Instancing Raycast
three.js · Runnable Example

Instancing Raycast

Runnable three.js example: Instancing Raycast. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All three.js examples
/demos/three-instancing-raycast.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-instancing-raycast.html
<!--
  说明:两千个实例化方块,鼠标扫过时只改被指到的那一个的颜色
  核心逻辑:InstancedMesh 的 raycast 返回 instanceId,setColorAt 单独改这一个
  依赖:three.js 0.160.0、OrbitControls · jsDelivr CDN(ESM + importmap)
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>实例化拾取</title>
<style>
  html,body{height:100%;margin:0;background:#0a0f14}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600;font-variant-numeric:tabular-nums}
  .bar .sp{flex:1 1 auto}
  #stage{flex:1 1 auto;min-height:0;position:relative;cursor:pointer}
  #stage canvas{display:block}
  #hud{position:absolute;left:12px;bottom:12px;padding:8px 12px;border-radius:6px;
       background:rgba(13,19,26,.84);border:1px solid #223040;font-size:12px;line-height:1.8;
       color:#c8d2e0;pointer-events:none;font-variant-numeric:tabular-nums}
  #hud em{font-style:normal;color:#ffd166}
</style>
</head>
<body>
<div class="bar">
  <span>实例 <b>2048</b></span>
  <span class="sp"></span>
  <span>移动鼠标拾取 · 点击锁定高亮 · 拖拽旋转</span>
</div>
<div id="stage">
  <div id="hud">当前实例 <em id="idx">无</em><br>网格坐标 <em id="grid">—</em></div>
</div>

<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0f14);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 200);
camera.position.set(16, 13, 18);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.8, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.48;
controls.update();

scene.add(new THREE.HemisphereLight(0xb4cee8, 0x101720, 1.4));
const sun = new THREE.DirectionalLight(0xffe9c9, 2.0);
sun.position.set(-12, 20, 9);
scene.add(sun);

const GRID = 64;
const COUNT = GRID * GRID;
const SPACING = 0.62;
const HALF = (GRID - 1) * SPACING / 2;

const geo = new THREE.BoxGeometry(0.42, 0.42, 0.42);
geo.translate(0, 0.21, 0);

const mesh = new THREE.InstancedMesh(
  geo,
  new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0.2 }),
  COUNT
);
scene.add(mesh);

const dummy = new THREE.Object3D();
const base = new THREE.Color();
const hi = new THREE.Color(0xffd166);

function baseColor(i) {
  const h = 0.4 + 0.22 * ((i % GRID) / GRID);
  return base.setHSL(h, 0.42, 0.34);
}

for (let i = 0; i < COUNT; i++) {
  const ix = i % GRID;
  const iz = (i / GRID) | 0;
  dummy.position.set(-HALF + ix * SPACING, 0, -HALF + iz * SPACING);
  dummy.scale.set(1, 0.6 + ((ix * 7 + iz * 13) % 9) * 0.16, 1);
  dummy.updateMatrix();
  mesh.setMatrixAt(i, dummy.matrix);
  mesh.setColorAt(i, baseColor(i));
}
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(44, 44),
  new THREE.MeshStandardMaterial({ color: 0x121a22, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.02;
scene.add(ground);

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(-10, -10);

const idxEl = document.getElementById('idx');
const gridEl = document.getElementById('grid');

let hovered = -1;
let locked = -1;

function restore(i) {
  if (i >= 0) mesh.setColorAt(i, baseColor(i));
}

function setHover(i) {
  if (i === hovered) return;
  restore(hovered);
  hovered = i;
  if (i >= 0) mesh.setColorAt(i, hi);
  mesh.instanceColor.needsUpdate = true;

  if (i >= 0) {
    idxEl.textContent = String(i);
    gridEl.textContent = '(' + (i % GRID) + ', ' + ((i / GRID) | 0) + ')';
  } else {
    idxEl.textContent = '无';
    gridEl.textContent = '—';
  }
}

function pick(event) {
  const r = renderer.domElement.getBoundingClientRect();
  pointer.x = ((event.clientX - r.left) / r.width) * 2 - 1;
  pointer.y = -((event.clientY - r.top) / r.height) * 2 + 1;

  raycaster.setFromCamera(pointer, camera);
  const hits = raycaster.intersectObject(mesh, false);
  setHover(hits.length ? hits[0].instanceId : -1);
}

renderer.domElement.addEventListener('pointermove', pick);
renderer.domElement.addEventListener('pointerleave', function () { setHover(-1); });

/* 点击锁定:锁定的实例保持高亮,鼠标移开也不复原 */
renderer.domElement.addEventListener('click', function (e) {
  pick(e);
  if (hovered >= 0) {
    restore(locked);
    locked = hovered;
    mesh.setColorAt(locked, hi);
    mesh.instanceColor.needsUpdate = true;
  } else {
    restore(locked);
    locked = -1;
    mesh.instanceColor.needsUpdate = true;
  }
});

/* 但悬停更新会覆盖锁定色,因此每次悬停前先把锁定色补回去 */
const oldSetHover = setHover;
setHover = function (i) {
  oldSetHover(i);
  if (locked >= 0) mesh.setColorAt(locked, hi);
  mesh.instanceColor.needsUpdate = true;
};

renderer.setAnimationLoop(function () {
  controls.update();
  renderer.render(scene, camera);
});

window.addEventListener('resize', function () {
  const w = stage.clientWidth;
  const h = stage.clientHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More three.js examples

three.js · EXAMPLEInstancing Scatter three.js · EXAMPLEInteractive Lines three.js · EXAMPLEInteractive Points