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

Raycast

Runnable three.js example: 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-raycast.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-raycast.html
<!--
  说明:鼠标移动与点击时用射线命中地面站点或数学平面,得到世界坐标并高亮要素
  核心逻辑:指针换算为归一化设备坐标 → setFromCamera 生成射线 → intersectObjects / intersectPlane
  依赖:three.js 0.160.0 · 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:#0d1117}
  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:12px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .bar .mono{font-family:ui-monospace,Consolas,monospace;color:#c8d2e0}
  .bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;cursor:pointer;
       border:1px solid #303845;background:#1d2531;color:#c8d2e0}
  .bar button:hover{background:#253040}
  .bar .sp{flex:1 1 auto}
  #stage{flex:1 1 auto;min-height:0;position:relative;cursor:default}
  #stage canvas{display:block}
</style>
</head>
<body>
<div class="bar">
  <span>悬停 <b id="hover">—</b></span>
  <span>拾取点 <span class="mono" id="hit">—</span></span>
  <span class="sp"></span>
  <button id="mode">模式:站点</button>
  <span>移动指针悬停 · 单击落点</span>
</div>
<div id="stage"></div>

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

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;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1016);
scene.fog = new THREE.Fog(0x0b1016, 45, 110);

const camera = new THREE.PerspectiveCamera(
  42, stage.clientWidth / stage.clientHeight, 0.5, 220
);
camera.position.set(0, 26, 34);
camera.lookAt(0, 0, 0);

scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x16202a, 1.15));
const sun = new THREE.DirectionalLight(0xfff0d8, 2.0);
sun.position.set(-16, 30, 18);
scene.add(sun);

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(64, 64),
  new THREE.MeshStandardMaterial({ color: 0x18222c, roughness: 0.96 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

/* 站点:锥体,每个实例共享几何体、材质各自一份以便单独高亮 */
const coneGeo = new THREE.ConeGeometry(0.7, 2.2, 10);
const markers = [];

for (let i = 0; i < 60; i++) {
  const a = i * 2.39996;
  const r = 4 + Math.sqrt(i) * 1.9;
  const mesh = new THREE.Mesh(
    coneGeo,
    new THREE.MeshStandardMaterial({
      color: new THREE.Color().setHSL(0.56 + (i % 7) * 0.012, 0.45, 0.52),
      roughness: 0.5,
      metalness: 0.1
    })
  );
  mesh.position.set(Math.cos(a) * r, 1.1, Math.sin(a) * r);
  mesh.name = '站点 ' + String(i + 1).padStart(2, '0');
  markers.push(mesh);
  scene.add(mesh);
}

/* 落点标记:贴地的圆环 */
const ring = new THREE.Mesh(
  new THREE.RingGeometry(1.05, 1.4, 40),
  new THREE.MeshBasicMaterial({ color: 0xf0b429, side: THREE.DoubleSide })
);
ring.rotation.x = -Math.PI / 2;
ring.visible = false;
scene.add(ring);

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planeHit = new THREE.Vector3();
const fmt = new THREE.Vector3();

const hoverEl = document.getElementById('hover');
const hitEl = document.getElementById('hit');
const modeBtn = document.getElementById('mode');

let mode = 'marker';   // marker | ground
let hovered = null;

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

function setHovered(obj) {
  if (hovered === obj) return;

  if (hovered) {
    hovered.material.emissive.setHex(0x000000);
    hovered.scale.setScalar(1);
  }

  hovered = obj;

  if (hovered) {
    hovered.material.emissive.setHex(0x2f6dff);
    hovered.scale.setScalar(1.25);
  }

  hoverEl.textContent = hovered ? hovered.name : '—';
  renderer.domElement.style.cursor = hovered ? 'pointer' : 'default';
}

function pickHover() {
  if (mode !== 'marker') {
    setHovered(null);
    return;
  }

  raycaster.setFromCamera(pointer, camera);
  const hits = raycaster.intersectObjects(markers, false);
  setHovered(hits.length ? hits[0].object : null);
}

renderer.domElement.addEventListener('pointermove', function (event) {
  updatePointer(event);
  pickHover();
});

renderer.domElement.addEventListener('pointerdown', function (event) {
  updatePointer(event);
  raycaster.setFromCamera(pointer, camera);

  let point = null;

  if (mode === 'marker') {
    const hits = raycaster.intersectObjects(markers, false);
    if (hits.length) point = hits[0].point;
  } else if (raycaster.ray.intersectPlane(groundPlane, planeHit)) {
    point = planeHit;
  }

  if (!point) {
    ring.visible = false;
    hitEl.textContent = '—';
    return;
  }

  ring.position.set(point.x, 0.04, point.z);
  ring.visible = true;

  fmt.copy(point);
  hitEl.textContent = 'x ' + fmt.x.toFixed(2) +
    ' · z ' + fmt.z.toFixed(2) + ' · y ' + fmt.y.toFixed(2);
});

modeBtn.addEventListener('click', function () {
  mode = mode === 'marker' ? 'ground' : 'marker';
  modeBtn.textContent = mode === 'marker' ? '模式:站点' : '模式:地面';
  setHovered(null);
});

renderer.setAnimationLoop(function () {
  /* 让站点轻轻起伏,高亮时更有辨识度 */
  const t = performance.now() * 0.001;
  for (let i = 0; i < markers.length; i++) {
    markers[i].position.y = 1.1 + Math.sin(t * 1.6 + i * 0.4) * 0.12;
  }
  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 · EXAMPLERaycaster Texture three.js · EXAMPLEShadow three.js · EXAMPLEShadow Pointlight