Terrain Raycast
Runnable three.js example: Terrain Raycast. 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
<!--
说明:鼠标在地形上滑动时实时求交,把屏幕像素换成世界坐标与海拔读数
核心逻辑:Raycaster 对地形 Mesh 求交,命中点 world 坐标反算到高程函数校验
依赖: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:#0c1016}
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:16px;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:crosshair}
#stage canvas{display:block}
#readout{position:absolute;left:12px;bottom:12px;padding:8px 12px;border-radius:6px;
background:rgba(13,19,26,.86);border:1px solid #223040;font-size:12px;line-height:1.7;
color:#c8d2e0;pointer-events:none;font-variant-numeric:tabular-nums}
#readout span{color:#7fd1a6}
</style>
</head>
<body>
<div class="bar">
<span>X <b id="px">—</b></span>
<span>Z <b id="pz">—</b></span>
<span>海拔 <b id="ph">—</b></span>
<span class="sp"></span>
<span>移动鼠标取点 · 点击放置标记 · 拖拽旋转</span>
</div>
<div id="stage">
<div id="readout">命中点:<span id="hit">未命中</span></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;
renderer.toneMappingExposure = 1.05;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c1016);
scene.fog = new THREE.Fog(0x0c1016, 40, 80);
const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(19, 14, 22);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1.2, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.update();
scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x111b16, 1.2));
const sun = new THREE.DirectionalLight(0xffeccd, 2.2);
sun.position.set(-16, 24, 12);
scene.add(sun);
const SIZE = 30;
const SEG = 120;
function heightAt(x, z) {
const a = 1.5 * Math.sin(x * 0.35) * Math.cos(z * 0.3);
const b = 0.9 * Math.sin(x * 0.8 + z * 0.6);
const c = 3.2 * Math.exp(-((x - 2) * (x - 2) + (z + 3) * (z + 3)) / 30);
return a + b + c;
}
const geo = new THREE.PlaneGeometry(SIZE, SIZE, SEG, SEG);
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position;
const colors = new Float32Array(pos.count * 3);
const col = new THREE.Color();
let minH = Infinity;
let maxH = -Infinity;
for (let i = 0; i < pos.count; i++) {
const h = heightAt(pos.getX(i), pos.getZ(i));
pos.setY(i, h);
minH = Math.min(minH, h);
maxH = Math.max(maxH, h);
}
for (let i = 0; i < pos.count; i++) {
const t = (pos.getY(i) - minH) / (maxH - minH);
col.setHSL(0.36 - 0.34 * t, 0.4 + 0.15 * t, 0.22 + 0.5 * t);
colors[i * 3] = col.r;
colors[i * 3 + 1] = col.g;
colors[i * 3 + 2] = col.b;
}
geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
geo.computeVertexNormals();
const terrain = new THREE.Mesh(
geo,
new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95, metalness: 0.02 })
);
scene.add(terrain);
/* 命中标记:一个圆环 + 一根竖直短线 */
const marker = new THREE.Group();
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.22, 0.34, 32),
new THREE.MeshBasicMaterial({ color: 0x5ef2a0, side: THREE.DoubleSide })
);
ring.rotation.x = -Math.PI / 2;
marker.add(ring);
const stick = new THREE.Mesh(
new THREE.CylinderGeometry(0.02, 0.02, 1.1, 6),
new THREE.MeshBasicMaterial({ color: 0x5ef2a0 })
);
stick.position.y = 0.55;
marker.add(stick);
marker.visible = false;
scene.add(marker);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(-2, -2);
const pxEl = document.getElementById('px');
const pzEl = document.getElementById('pz');
const phEl = document.getElementById('ph');
const hitEl = document.getElementById('hit');
function toLocal(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;
}
function pick() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(terrain, false);
if (!hits.length) {
hitEl.textContent = '未命中';
pxEl.textContent = pzEl.textContent = phEl.textContent = '—';
marker.visible = false;
return null;
}
const p = hits[0].point;
marker.position.copy(p);
marker.visible = true;
pxEl.textContent = p.x.toFixed(2);
pzEl.textContent = p.z.toFixed(2);
phEl.textContent = p.y.toFixed(2);
hitEl.textContent = '(' + p.x.toFixed(1) + ', ' + p.z.toFixed(1) + ') 高 ' + p.y.toFixed(2);
return p;
}
renderer.domElement.addEventListener('pointermove', function (e) {
toLocal(e);
pick();
});
renderer.domElement.addEventListener('pointerleave', function () {
marker.visible = false;
hitEl.textContent = '未命中';
});
/* 点击时在命中点加一根固定标柱,证明屏幕坐标到世界坐标的换算可用 */
const pins = new THREE.Group();
scene.add(pins);
renderer.domElement.addEventListener('click', function (e) {
toLocal(e);
const p = pick();
if (!p) return;
if (pins.children.length > 24) pins.remove(pins.children[0]);
const pin = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.05, 1.6, 8),
new THREE.MeshStandardMaterial({ color: 0xffd166, roughness: 0.5 })
);
pin.position.set(p.x, p.y + 0.8, p.z);
pins.add(pin);
});
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.