全部效果悬停与跟随

交互三维地球

Interactive Globe

拖动可旋转三维地球,地球上标出发光地点和弧形连线。

拖动地球,或按方向键旋转

适用场景

展示全球业务、基础设施或分布式团队所在的地区。 把节点数量控制在一眼能分辨的范围内,同时支持拖动和键盘旋转。

应用示例

分布式存储平台在地球上标出主要数据中心,访客可旋转地球,查看地区之间的连线。

也叫

  • 三维地球
  • 可旋转地球

AI 提示词

给【区块】加上交互三维地球。支持拖动或方向键旋转,标出几个发光地点,可用弧线相连。空闲时缓慢自转。减少动态效果模式下停止自转并保留手动操作。

示例代码

保存为 HTML 文件后,用浏览器打开即可运行。代码与页面里的演示一致。

查看 HTML
<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>交互三维地球</title>
  <style>
    :root {
      color-scheme: dark;
      --demo-bg: #171629;
      --demo-ink: #f8f5ff;
      --demo-accent: #b9a6ff;
      --demo-muted: #bfbbd3;
      font-family: system-ui, sans-serif;
      color: var(--demo-ink);
      background: var(--demo-bg);
    }

    *, *::before, *::after { box-sizing: border-box; }
    body { margin: 0; min-width: 0; }
    button, input { font: inherit; }

    .demo {
      display: grid;
      place-items: center;
      align-content: center;
      min-height: 100vh;
      padding: 14px;
      overflow: hidden;
      background: radial-gradient(ellipse at 50% 24%, #28233f, var(--demo-bg) 78%);
    }

    .demo-button {
      border: 1px solid #ffffff3d;
      border-radius: 7px;
      background: #ffffff12;
      color: var(--demo-ink);
      padding: 6px 11px;
      font-size: 12px;
      cursor: pointer;
    }

    :focus-visible {
      outline: 2px solid var(--demo-accent);
      outline-offset: 3px;
    }

    .demo {
      background:
        radial-gradient(ellipse at 50% 0%, #15334b 0, #0d1b2d 50%, #080f1d 100%);
    }
    .globe-scene {
      position: relative; width: min(100%, 490px);
      height: clamp(120px, calc(100vh - 28px), 350px);
    }
    .globe-scene canvas {
      display: block; width: 100%; height: 100%; cursor: grab; touch-action: none;
      background: radial-gradient(circle, #214762 0%, transparent 68%);
      border-radius: 12px;
    }
    .globe-scene canvas:active { cursor: grabbing; }
    [data-globe-toggle] {
      position: absolute; right: 0; bottom: 0;
      border-color: #547590; background: #102539; color: #d1e8f4;
    }
    @media (prefers-reduced-motion: reduce) {
      [data-globe-toggle] { display: none; }
    }
  </style>
</head>
<body>
  <main class="demo">
    <div class="globe-scene">
      <canvas width="432" height="330" tabindex="0" aria-label="三维地球,可拖动或用方向键旋转"></canvas>
      <button class="demo-button" type="button" data-globe-toggle>暂停旋转</button>
    </div>
  </main>
  <script>
    const canvas = document.querySelector('canvas');
    const context = canvas.getContext('2d');
    const toggle = document.querySelector('[data-globe-toggle]');
    const reduced = matchMedia('(prefers-reduced-motion: reduce)');

    // Simplified coastlines in longitude and latitude.
    const land = [
      [[-166,65],[-142,72],[-110,72],[-87,78],[-58,61],[-62,48],[-80,32],[-96,18],[-111,23],[-126,42],[-128,55],[-147,60]],
      [[-99,20],[-84,18],[-76,8],[-81,8],[-89,15]],
      [[-81,9],[-68,12],[-52,3],[-35,-7],[-39,-21],[-56,-32],[-65,-54],[-74,-46],[-78,-16]],
      [[-54,60],[-42,60],[-20,72],[-21,81],[-49,84],[-66,77]],
      [[-10,36],[-6,48],[10,57],[5,62],[21,71],[40,69],[66,75],[99,79],[119,76],[159,70],[179,63],[163,56],[145,49],[134,38],[122,28],[117,12],[101,2],[96,17],[86,22],[77,7],[70,23],[58,26],[47,29],[47,14],[37,18],[31,30],[25,37],[15,39],[12,45]],
      [[-17,15],[-16,29],[-4,36],[14,37],[32,31],[44,12],[50,11],[42,-11],[34,-24],[25,-35],[15,-30],[9,-12],[8,3],[-4,5],[-13,8]],
      [[111,-21],[117,-13],[132,-12],[138,-17],[146,-12],[154,-28],[146,-39],[132,-34],[115,-36]],
      [[97,5],[108,6],[121,0],[126,-9],[110,-8],[101,-4]],
      [[137,38],[145,44],[144,36],[133,31]],
      [[46,-13],[51,-16],[46,-26],[43,-22]],
      [[165,-43],[177,-36],[178,-40],[168,-48]],
    ];
    const cities = [[-74,41],[-123,49],[-47,-23],[0,51],[31,30],[103,1],[139,36],[151,-34]];
    const connections = [[0,3],[0,2],[1,0],[3,4],[4,5],[5,6],[5,7]];
    const radians = Math.PI / 180;
    const points = [];
    for (let latitude = -81; latitude <= 81; latitude += 3) {
      const step = 3 / Math.cos(latitude * radians);
      for (let longitude = -180; longitude < 180; longitude += step) {
        if (land.some((coast) => contains(coast, longitude, latitude))) {
          points.push(vector(longitude, latitude));
        }
      }
    }

    function contains(outline, x, y) {
      let inside = false;
      for (let i = 0, previous = outline.length - 1; i < outline.length; previous = i++) {
        const [x1, y1] = outline[i];
        const [x2, y2] = outline[previous];
        if ((y1 > y) !== (y2 > y) && x < (x2 - x1) * (y - y1) / (y2 - y1) + x1) {
          inside = !inside;
        }
      }
      return inside;
    }

    function vector(longitude, latitude) {
      const lon = longitude * radians;
      const lat = latitude * radians;
      return [Math.cos(lat) * Math.sin(lon), Math.sin(lat), Math.cos(lat) * Math.cos(lon)];
    }

    const cityVectors = cities.map(([lon, lat]) => vector(lon, lat));
    const arcPoints = connections.map(([start, end]) => {
      const a = cityVectors[start];
      const b = cityVectors[end];
      return Array.from({ length: 25 }, (_, index) => {
        const fraction = index / 24;
        const point = a.map((coordinate, axis) => coordinate * (1 - fraction) + b[axis] * fraction);
        const elevation = (1 + .09 * Math.sin(Math.PI * fraction)) / Math.hypot(...point);
        return point.map((coordinate) => coordinate * elevation);
      });
    });
    const gridLines = [];
    for (let latitude = -60; latitude <= 60; latitude += 30) {
      gridLines.push(Array.from({length: 73}, (_, i) => vector(i * 5, latitude)));
    }
    for (let longitude = 0; longitude < 360; longitude += 30) {
      gridLines.push(Array.from({length: 37}, (_, i) => vector(longitude, i * 5 - 90)));
    }

    let yaw = .53;
    let pitch = -.24;
    let radius;
    let centerX;
    let centerY;
    let frame = 0;
    let lastFrame = 0;
    let pointer;
    let playing = true;
    let inView = true;

    function draw() {
      if (!context) return;
      const width = canvas.clientWidth;
      const height = canvas.clientHeight;
      if (!width || !height) return;
      const density = Math.min(devicePixelRatio || 1, 2);
      const pixelsWide = Math.round(width * density);
      const pixelsHigh = Math.round(height * density);
      if (canvas.width !== pixelsWide || canvas.height !== pixelsHigh) {
        canvas.width = pixelsWide;
        canvas.height = pixelsHigh;
      }

      context.setTransform(density, 0, 0, density, 0, 0);
      context.clearRect(0, 0, width, height);
      radius = Math.min(width * .3, height * .43);
      centerX = width * .5;
      centerY = height * .47;
      const cosYaw = Math.cos(yaw);
      const sinYaw = Math.sin(yaw);
      const cosPitch = Math.cos(pitch);
      const sinPitch = Math.sin(pitch);
      function project([x, y, z]) {
        const px = x * cosYaw + z * sinYaw;
        const pz = z * cosYaw - x * sinYaw;
        return [centerX + px * radius, centerY - (y * cosPitch - pz * sinPitch) * radius, y * sinPitch + pz * cosPitch];
      }

      const ocean = context.createRadialGradient(centerX - radius * .37, centerY - radius * .42, 0, centerX, centerY, radius * 1.14);
      ocean.addColorStop(0, '#295677');
      ocean.addColorStop(.66, '#172f49');
      ocean.addColorStop(1, '#081526');
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      context.fillStyle = ocean;
      context.shadowColor = '#609ee7a6';
      context.shadowBlur = 17;
      context.fill();
      context.shadowBlur = 0;
      context.lineWidth = 1;
      context.strokeStyle = '#6595bd';
      context.stroke();

      function trace(line) {
        let penDown = false;
        for (const point of line) {
          const [x, y, depth] = project(point);
          if (depth < 0) {
            penDown = false;
          } else if (penDown) {
            context.lineTo(x, y);
          } else {
            context.moveTo(x, y);
            penDown = true;
          }
        }
      }

      context.beginPath();
      gridLines.forEach(trace);
      context.strokeStyle = '#77abd535';
      context.lineWidth = .6;
      context.stroke();
      context.fillStyle = '#70d7d0';
      for (const point of points) {
        const [x, y, depth] = project(point);
        if (depth <= 0) continue;
        context.globalAlpha = .18 + depth * .68;
        const size = .6 + depth * radius * .019;
        context.fillRect(x - size / 2, y - size / 2, size, size);
      }
      context.globalAlpha = 1;
      context.beginPath();
      arcPoints.forEach(trace);
      context.strokeStyle = '#f6ba77a8';
      context.lineWidth = .85;
      context.stroke();

      for (const city of cityVectors) {
        const [x, y, depth] = project(city);
        if (depth <= .03) continue;
        context.beginPath();
        context.arc(x, y, 4, 0, 2 * Math.PI);
        context.fillStyle = '#ffd29350';
        context.fill();
        context.beginPath();
        context.arc(x, y, 2, 0, 2 * Math.PI);
        context.fillStyle = '#ffe1ad';
        context.fill();
      }
    }

    function tick(time) {
      if (lastFrame && time - lastFrame < 32) {
        frame = requestAnimationFrame(tick);
        return;
      }
      if (lastFrame) yaw -= Math.min(time - lastFrame, 60) * .00025;
      lastFrame = time;
      draw();
      frame = requestAnimationFrame(tick);
    }

    function updateMotion() {
      cancelAnimationFrame(frame);
      lastFrame = 0;
      if (context && playing && inView && !pointer && !reduced.matches && !document.hidden) {
        frame = requestAnimationFrame(tick);
      }
    }

    function rotate(dx, dy) {
      yaw += dx;
      pitch = Math.max(-1.37, Math.min(1.37, pitch + dy));
      draw();
    }

    canvas.addEventListener('pointerdown', (event) => {
      if (pointer || event.button !== 0) return;
      canvas.setPointerCapture(event.pointerId);
      pointer = { id: event.pointerId, x: event.clientX, y: event.clientY };
      updateMotion();
    });
    canvas.addEventListener('pointermove', (event) => {
      if (event.pointerId !== pointer?.id) return;
      rotate((event.clientX - pointer.x) * .012, (event.clientY - pointer.y) * .012);
      pointer.x = event.clientX;
      pointer.y = event.clientY;
    });
    canvas.addEventListener('lostpointercapture', (event) => {
      if (event.pointerId !== pointer?.id) return;
      pointer = undefined;
      updateMotion();
    });
    canvas.addEventListener('keydown', (event) => {
      const steps = { ArrowLeft: [-.19, 0], ArrowRight: [.19, 0], ArrowUp: [0, -.15], ArrowDown: [0, .15] };
      const step = steps[event.key];
      if (!step) return;
      event.preventDefault();
      rotate(...step);
    });
    toggle.addEventListener('click', () => {
      playing = !playing;
      toggle.textContent = playing ? "暂停旋转" : "开始旋转";
      updateMotion();
    });
    reduced.addEventListener('change', updateMotion);
    document.addEventListener('visibilitychange', updateMotion);
    new ResizeObserver(draw).observe(canvas);
    new IntersectionObserver(([entry]) => {
      inView = entry.isIntersecting;
      updateMotion();
    }).observe(canvas);
    draw();
    updateMotion();
  </script>
</body>
</html>

UI Skills 原创示例