Interactive Lines
Runnable three.js example: Interactive Lines. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
说明:一张线网里挑出鼠标最近的一段,用一段独立高亮线盖住它并显示端点坐标
核心逻辑:LineSegments 的射线阈值把「压线」放宽,命中结果带 segment 索引
依赖: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:#07101a}
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 input[type=range]{width:150px;accent-color:#4f9ef8}
.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 id="cnt">0</b></span>
<label>阈值 <input type="range" id="thr" min="0.1" max="1.4" step="0.05" value="0.45"></label>
<span><b id="thrv">0.45</b></span>
<span class="sp"></span>
<span>移动鼠标拾取 · 拖拽旋转</span>
</div>
<div id="stage">
<div id="hud">命中段 <em id="seg">无</em><br>端点 <em id="ends">—</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;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101a);
scene.fog = new THREE.Fog(0x07101a, 28, 58);
const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 200);
camera.position.set(13, 12, 16);
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(0xa8c8ef, 0x0e161c, 1.4));
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({ color: 0x101a22, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
function heightAt(x, z) {
return 0.6 * Math.sin(x * 0.4) * Math.cos(z * 0.35) + 0.3 * Math.sin(x * 0.9 + z * 0.7);
}
const GRID = 34;
const STEP = 1.15;
const HALF = (GRID * STEP) / 2;
const positions = [];
const segmentIndex = [];
function pushSeg(x1, z1, x2, z2) {
positions.push(x1, heightAt(x1, z1) + 0.1, z1, x2, heightAt(x2, z2) + 0.1, z2);
}
for (let ix = 0; ix < GRID; ix++) {
for (let iz = 0; iz < GRID; iz++) {
const x = -HALF + ix * STEP;
const z = -HALF + iz * STEP;
if ((ix + iz) % 3 !== 0) pushSeg(x, z, x + STEP, z);
if ((ix * 2 + iz) % 4 !== 0) pushSeg(x, z, x, z + STEP);
}
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
geo.computeBoundingSphere();
const net = new THREE.LineSegments(
geo,
new THREE.LineBasicMaterial({ color: 0x3f6d94, transparent: true, opacity: 0.72 })
);
scene.add(net);
const count = positions.length / 6;
document.getElementById('cnt').textContent = count.toLocaleString('en-US');
/* 高亮:单独一段线,位置每次命中时改写 */
const hiGeo = new THREE.BufferGeometry();
hiGeo.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0, 0, 0, 0], 3));
const hiLine = new THREE.LineSegments(
hiGeo,
new THREE.LineBasicMaterial({ color: 0xffd166, linewidth: 2 })
);
hiLine.visible = false;
scene.add(hiLine);
const raycaster = new THREE.Raycaster();
raycaster.params.Line = { threshold: 0.45 };
const pointer = new THREE.Vector2(-10, -10);
const segEl = document.getElementById('seg');
const endsEl = document.getElementById('ends');
const thrEl = document.getElementById('thr');
const thrvEl = document.getElementById('thrv');
thrEl.addEventListener('input', function () {
const v = Number(thrEl.value);
raycaster.params.Line.threshold = v;
thrvEl.textContent = v.toFixed(2);
});
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(net, false);
if (!hits.length) {
hiLine.visible = false;
segEl.textContent = '无';
endsEl.textContent = '—';
return;
}
const hit = hits[0];
/* LineSegments 的命中索引是顶点索引,除以 2 得到段号 */
const segIdx = Math.floor(hit.index / 2);
const a = segIdx * 6;
const arr = hiGeo.attributes.position.array;
for (let k = 0; k < 6; k++) arr[k] = positions[a + k];
hiGeo.attributes.position.needsUpdate = true;
hiGeo.computeBoundingSphere();
hiLine.visible = true;
segEl.textContent = String(segIdx) + '(距相机 ' + hit.distance.toFixed(1) + ')';
endsEl.textContent =
'(' + positions[a].toFixed(1) + ', ' + positions[a + 2].toFixed(1) + ') → (' +
positions[a + 3].toFixed(1) + ', ' + positions[a + 5].toFixed(1) + ')';
}
renderer.domElement.addEventListener('pointermove', pick);
renderer.domElement.addEventListener('pointerleave', function () {
hiLine.visible = false;
segEl.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);
});
</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.