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

Trajectory

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

Source

demos/three-trajectory.html
<!--
  说明:五个城市串成一条闭合航线,亮点沿曲线匀速前进,演示三维轨迹动画
  核心逻辑:经纬度采样点转球面坐标,CatmullRomCurve3 生成曲线,TubeGeometry 成管
  依赖: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:#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:10px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .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}
  #stage canvas{display:block}
</style>
</head>
<body>
<div class="bar">
  <span>进度 <b id="pct">0%</b></span>
  <button id="pause">暂停飞行</button>
  <button id="grid">隐藏经纬网</button>
  <span class="sp"></span>
  <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",
    "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(0x070b10);

const camera = new THREE.PerspectiveCamera(
  42, stage.clientWidth / stage.clientHeight, 0.05, 100
);
camera.position.set(2.0, 1.7, 3.3);

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.07;
controls.minDistance = 2.2;
controls.maxDistance = 12;
controls.target.set(0, 0, 0);
controls.update();

scene.add(new THREE.AmbientLight(0xffffff, 0.85));
const sun = new THREE.DirectionalLight(0xfff2dc, 1.8);
sun.position.set(4, 6, 3);
scene.add(sun);

const R = 1.6;

function lonLatToVec3(lon, lat, radius) {
  const phi = (90 - lat) * Math.PI / 180;
  const theta = (lon + 180) * Math.PI / 180;
  return new THREE.Vector3(
    -radius * Math.sin(phi) * Math.cos(theta),
     radius * Math.cos(phi),
     radius * Math.sin(phi) * Math.sin(theta)
  );
}

/* 所有球面对象放进同一个组,初始转半圈让中国区域朝向镜头 */
const earth = new THREE.Group();
earth.rotation.y = Math.PI;
scene.add(earth);

/* 素色球体,把视觉重点留给轨迹 */
const globe = new THREE.Mesh(
  new THREE.SphereGeometry(R, 96, 64),
  new THREE.MeshStandardMaterial({
    color: 0x1b3a57,
    roughness: 0.9,
    metalness: 0.04
  })
);
earth.add(globe);

/* 经纬网用线段成对构造,每 30 度一条 */
function buildGraticule(radius) {
  const pts = [];
  const step = 5;

  for (let lat = -60; lat <= 60; lat += 30) {
    for (let lon = -180; lon < 180; lon += step) {
      pts.push(
        lonLatToVec3(lon, lat, radius),
        lonLatToVec3(lon + step, lat, radius)
      );
    }
  }

  for (let lon = -180; lon < 180; lon += 30) {
    for (let lat = -85; lat < 85; lat += step) {
      pts.push(
        lonLatToVec3(lon, lat, radius),
        lonLatToVec3(lon, lat + step, radius)
      );
    }
  }

  const geo = new THREE.BufferGeometry().setFromPoints(pts);
  return new THREE.LineSegments(
    geo,
    new THREE.LineBasicMaterial({
      color: 0x2f5470,
      transparent: true,
      opacity: 0.75
    })
  );
}

const graticule = buildGraticule(R * 1.002);
earth.add(graticule);

const cities = [
  { name: '北京', lon: 116.39, lat: 39.91 },
  { name: '上海', lon: 121.47, lat: 31.23 },
  { name: '广州', lon: 113.26, lat: 23.13 },
  { name: '成都', lon: 104.06, lat: 30.67 },
  { name: '西安', lon: 108.94, lat: 34.34 }
];

/* 航线抬到球面之上,避免管道贴住球体产生穿插 */
const routePoints = cities.map(function (c) {
  return lonLatToVec3(c.lon, c.lat, R * 1.06);
});

const curve = new THREE.CatmullRomCurve3(routePoints, true, 'centripetal', 0.5);

const tube = new THREE.Mesh(
  new THREE.TubeGeometry(curve, 360, 0.012, 8, true),
  new THREE.MeshBasicMaterial({ color: 0x4fc3ff })
);
earth.add(tube);

const markerGeo = new THREE.SphereGeometry(0.02, 10, 10);
const markerMat = new THREE.MeshBasicMaterial({ color: 0x9fd8ff });

cities.forEach(function (c) {
  const dot = new THREE.Mesh(markerGeo, markerMat);
  dot.position.copy(lonLatToVec3(c.lon, c.lat, R * 1.005));
  earth.add(dot);
});

/* 沿曲线运动的亮点 */
const flyer = new THREE.Mesh(
  new THREE.SphereGeometry(0.038, 16, 16),
  new THREE.MeshBasicMaterial({ color: 0xffd166 })
);
earth.add(flyer);

/* 尾迹:保留最近若干采样位置,形成一条渐隐的短线 */
const TRAIL = 40;
const trailPositions = new Float32Array(TRAIL * 3);
const trailGeo = new THREE.BufferGeometry();
trailGeo.setAttribute('position', new THREE.BufferAttribute(trailPositions, 3));
const trail = new THREE.Line(
  trailGeo,
  new THREE.LineBasicMaterial({ color: 0xffd166, transparent: true, opacity: 0.6 })
);
earth.add(trail);

let progress = 0;
let running = true;
let fill = 0;
const pct = document.getElementById('pct');
const clock = new THREE.Clock();

/* 尾迹先填满起点,避免第一帧出现一条来自原点的线 */
const startPoint = curve.getPointAt(0);
for (let i = 0; i < TRAIL; i++) {
  trailPositions[i * 3] = startPoint.x;
  trailPositions[i * 3 + 1] = startPoint.y;
  trailPositions[i * 3 + 2] = startPoint.z;
}
trailGeo.attributes.position.needsUpdate = true;

renderer.setAnimationLoop(function () {
  const dt = Math.min(clock.getDelta(), 0.05);

  if (running) {
    progress = (progress + dt * 0.11) % 1;
  }

  const p = curve.getPointAt(progress);
  flyer.position.copy(p);

  /* 环形缓冲区:新点覆盖最旧的点,构成拖尾 */
  for (let i = 0; i < TRAIL - 1; i++) {
    trailPositions[i * 3] = trailPositions[(i + 1) * 3];
    trailPositions[i * 3 + 1] = trailPositions[(i + 1) * 3 + 1];
    trailPositions[i * 3 + 2] = trailPositions[(i + 1) * 3 + 2];
  }
  trailPositions[(TRAIL - 1) * 3] = p.x;
  trailPositions[(TRAIL - 1) * 3 + 1] = p.y;
  trailPositions[(TRAIL - 1) * 3 + 2] = p.z;
  trailGeo.attributes.position.needsUpdate = true;

  fill++;
  if (fill % 6 === 0) {
    pct.textContent = Math.round(progress * 100) + '%';
  }

  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);
});

const pauseBtn = document.getElementById('pause');
pauseBtn.addEventListener('click', function () {
  running = !running;
  pauseBtn.textContent = running ? '暂停飞行' : '继续飞行';
});

const gridBtn = document.getElementById('grid');
let gridOn = true;
gridBtn.addEventListener('click', function () {
  gridOn = !gridOn;
  graticule.visible = gridOn;
  gridBtn.textContent = gridOn ? '隐藏经纬网' : '显示经纬网';
});
</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 · EXAMPLEWater three.js · EXAMPLEAnimation Blend three.js · EXAMPLEAxes