Atlaslog
Atlaslog / Examples / three.js / Raycaster Texture
three.js · Runnable Example

Raycaster Texture

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

Source

demos/three-raycaster-texture.html
<!--
  说明:点击地面贴图上的任意位置,取出该像素的 UV 与绑定的地块编号
  核心逻辑:射线交点自带 uv,用它反查 canvas 数据,同时把标记放在三维空间中
  依赖: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:#0a1116}
  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 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:crosshair}
  #stage canvas{display:block}
  #hud{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.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>点击地面取地块</span>
  <button id="clear">清除标记</button>
  <span class="sp"></span>
  <span>拖拽旋转 · 滚轮缩放</span>
</div>
<div id="stage">
  <div id="hud">UV <em id="uv">—</em><br>像素 <em id="px">—</em><br>地块编号 <em id="parcel">—</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(0x0a1116);

const camera = new THREE.PerspectiveCamera(42, stage.clientWidth / stage.clientHeight, 0.1, 200);
camera.position.set(0, 26, 22);

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

scene.add(new THREE.HemisphereLight(0xbcd6f2, 0x101820, 1.4));

/* 地块贴图:8 × 8 的网格,每格填一种色,格内再画一条细边与编号 */
const GRID = 8;
const SIZE = 512;
const CELL = SIZE / GRID;
const parcelIds = [];

const cv = document.createElement('canvas');
cv.width = cv.height = SIZE;
const ctx = cv.getContext('2d');

function hash(n) {
  const x = Math.sin(n * 45.13 + 7.9) * 43758.5453;
  return x - Math.floor(x);
}

for (let y = 0; y < GRID; y++) {
  for (let x = 0; x < GRID; x++) {
    const id = y * GRID + x;
    const hue = 190 + hash(id) * 80;
    const light = 24 + hash(id + 3) * 16;
    ctx.fillStyle = 'hsl(' + hue + ', 34%, ' + light + '%)';
    ctx.fillRect(x * CELL, y * CELL, CELL, CELL);

    ctx.strokeStyle = 'rgba(140, 200, 240, 0.42)';
    ctx.lineWidth = 2;
    ctx.strokeRect(x * CELL + 1, y * CELL + 1, CELL - 2, CELL - 2);

    ctx.fillStyle = 'rgba(220, 236, 250, 0.72)';
    ctx.font = 'bold 18px sans-serif';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    ctx.fillText(String(id), x * CELL + 10, y * CELL + 8);

    parcelIds.push(id);
  }
}

const tex = new THREE.CanvasTexture(cv);
tex.colorSpace = THREE.SRGBColorSpace;
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(16, 16),
  new THREE.MeshStandardMaterial({ map: tex, roughness: 0.92, metalness: 0.02 })
);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

/* 标记:一串竖直的细柱 + 顶部小球 */
const markers = new THREE.Group();
scene.add(markers);

const markMat = new THREE.MeshStandardMaterial({ color: 0xffd166, roughness: 0.4 });
const ballGeo = new THREE.SphereGeometry(0.13, 12, 8);
const rodGeo = new THREE.CylinderGeometry(0.015, 0.015, 1, 6);
rodGeo.translate(0, 0.5, 0);

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const uvEl = document.getElementById('uv');
const pxEl = document.getElementById('px');
const parcelEl = document.getElementById('parcel');

function onClick(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(ground, false);
  if (!hits.length) return;

  const hit = hits[0];
  const uv = hit.uv;

  /* UV 在 [0,1],canvas 的 y 轴向下,所以要翻过来 */
  const pxX = Math.min(SIZE - 1, Math.floor(uv.x * SIZE));
  const pxY = Math.min(SIZE - 1, Math.floor((1 - uv.y) * SIZE));
  const gx = Math.floor(pxX / CELL);
  const gy = Math.floor(pxY / CELL);
  const id = parcelIds[gy * GRID + gx];

  uvEl.textContent = '(' + uv.x.toFixed(3) + ', ' + uv.y.toFixed(3) + ')';
  pxEl.textContent = '(' + pxX + ', ' + pxY + ')';
  parcelEl.textContent = String(id) +
    '  (网格 ' + gx + ', ' + gy + ')';

  if (markers.children.length > 12) {
    markers.remove(markers.children[0]);
    markers.remove(markers.children[0]);
  }

  const rod = new THREE.Mesh(rodGeo, markMat);
  rod.position.copy(hit.point);
  markers.add(rod);

  const ball = new THREE.Mesh(ballGeo, markMat);
  ball.position.copy(hit.point).add(new THREE.Vector3(0, 1.02, 0));
  markers.add(ball);
}

renderer.domElement.addEventListener('click', onClick);

document.getElementById('clear').addEventListener('click', function () {
  while (markers.children.length) markers.remove(markers.children[0]);
  uvEl.textContent = '—';
  pxEl.textContent = '—';
  parcelEl.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.

More three.js examples

three.js · EXAMPLEShadow three.js · EXAMPLEShadow Pointlight three.js · EXAMPLEShadow Viewer