Atlaslog
Atlaslog / Examples / three.js / Lines Rays
three.js · Runnable Example

Lines Rays

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

Source

demos/three-lines-rays.html
<!--
  说明:粗线也能被射线拾取,鼠标靠近哪条管网,哪条就变色并显示编号
  核心逻辑:Line2 的 raycast 读取 instanceStart/End 索引,命中结果带 line 索引
  依赖:three.js 0.160.0、OrbitControls、Line2 · 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:#0b1015}
  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}
  .bar .sp{flex:1 1 auto}
  #stage{flex:1 1 auto;min-height:0;position:relative;cursor:crosshair}
  #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:#7fd1a6}
</style>
</head>
<body>
<div class="bar">
  <span>管线 <b>8</b> 条</span>
  <span class="sp"></span>
  <span>移动鼠标靠近管线拾取 · 拖拽旋转</span>
</div>
<div id="stage">
  <div id="hud">命中 <em id="hit">无</em><br>阈值 <em id="thr">—</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';
import { Line2 } from 'three/addons/lines/Line2.js';
import { LineGeometry } from 'three/addons/lines/LineGeometry.js';
import { LineMaterial } from 'three/addons/lines/LineMaterial.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;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1015);
scene.fog = new THREE.Fog(0x0b1015, 40, 78);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(15, 17, 20);

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

scene.add(new THREE.HemisphereLight(0xbcd4f0, 0x121b22, 1.35));
const sun = new THREE.DirectionalLight(0xffe8c6, 1.9);
sun.position.set(-12, 22, 9);
scene.add(sun);

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

const grid = new THREE.GridHelper(54, 54, 0x1d2a37, 0x141d25);
grid.position.y = 0.008;
scene.add(grid);

const BASE = 0x4f9ef8;
const HOT = 0xffd166;

const lines = [];

function makePath(seed) {
  const arr = [];
  const n = 10;
  for (let i = 0; i <= n; i++) {
    const t = i / n;
    arr.push(
      THREE.MathUtils.lerp(-16, 16, t) + Math.sin(t * 5 + seed) * 2.2,
      1.5 + Math.sin(t * 3.4 + seed) * 1.4,
      Math.sin(t * 4.2 + seed * 1.7) * 6
    );
  }
  return arr;
}

for (let i = 0; i < 8; i++) {
  const geo = new LineGeometry();
  geo.setPositions(makePath(i * 1.3));

  const mat = new LineMaterial({
    color: BASE,
    linewidth: 4.5,
    transparent: true,
    opacity: 0.9
  });
  mat.resolution.set(stage.clientWidth, stage.clientHeight);

  const line = new Line2(geo, mat);
  line.computeLineDistances();
  line.userData.index = i;
  line.userData.baseColor = BASE;
  scene.add(line);
  lines.push(line);
}

/* 竖直标柱,标出每条管线的起点编号 */
const labelCanvas = document.createElement('canvas');
labelCanvas.width = labelCanvas.height = 64;
const labelCtx = labelCanvas.getContext('2d');
const labels = [];
for (let i = 0; i < 8; i++) {
  labelCtx.clearRect(0, 0, 64, 64);
  labelCtx.fillStyle = '#0e151c';
  labelCtx.beginPath();
  labelCtx.arc(32, 32, 30, 0, Math.PI * 2);
  labelCtx.fill();
  labelCtx.strokeStyle = '#4f9ef8';
  labelCtx.lineWidth = 3;
  labelCtx.stroke();
  labelCtx.fillStyle = '#dfe9f5';
  labelCtx.font = 'bold 30px sans-serif';
  labelCtx.textAlign = 'center';
  labelCtx.textBaseline = 'middle';
  labelCtx.fillText(String(i + 1), 32, 35);

  const tex = new THREE.CanvasTexture(labelCanvas);
  tex.colorSpace = THREE.SRGBColorSpace;
  const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false }));
  const p = lines[i].geometry.attributes.instanceStart;
  sprite.position.set(
    p.data.array[0],
    p.data.array[1] + 1.1,
    p.data.array[2]
  );
  sprite.scale.set(1.1, 1.1, 1);
  scene.add(sprite);
  labels.push(sprite);
}

const raycaster = new THREE.Raycaster();
raycaster.params.Line2 = { threshold: 0.9 };

const pointer = new THREE.Vector2(-10, -10);
const hitEl = document.getElementById('hit');
document.getElementById('thr').textContent = raycaster.params.Line2.threshold.toFixed(1);

function resetColors() {
  lines.forEach(function (l) {
    l.material.color.setHex(BASE);
    l.material.linewidth = 4.5;
  });
}

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.intersectObjects(lines, false);

  resetColors();

  if (!hits.length) {
    hitEl.textContent = '无';
    return;
  }

  const hit = hits[0];
  const obj = hit.object;
  obj.material.color.setHex(HOT);
  obj.material.linewidth = 7.5;
  hitEl.textContent = '管线 ' + (obj.userData.index + 1) +
    '(距相机 ' + hit.distance.toFixed(1) + ')';
}

renderer.domElement.addEventListener('pointermove', pick);
renderer.domElement.addEventListener('pointerleave', function () {
  resetColors();
  hitEl.textContent = '无';
});

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);
  lines.forEach(function (l) { l.material.resolution.set(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 · EXAMPLELOD three.js · EXAMPLEMaterials Canvas Texture three.js · EXAMPLEMaterials Displacement