使用 Three.js + Three-Tile 实现地球场景与几何体

185 阅读2分钟

使用 Three.js + Three-Tile 实现地球场景与几何体

前言

在 3D 可视化开发中,Three.js 是一个强大的 WebGL 库,而 Three-Tile 是基于 Three.js 封装的地形渲染库。本文将通过 Vue3 的 <script setup> 方式,结合 Three.js 和 Three-Tile,在地理位置上实现地球场景,并添加几何体。


项目环境

  • Vue3 + Vite
  • Three.js 0.165.0
  • Three-Tile 0.9.0

安装依赖

npm i three three-tile -S

核心功能实现

1. 创建 Vue 组件

<template>
  <div id="map"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as THREE from 'three';
import * as tt from 'three-tile';

// 创建球体模型
function createSphere(color) {
  const sphereGeometry = new THREE.SphereGeometry(2, 32, 32);
  const sphereMaterial = new THREE.MeshStandardMaterial({
    color,
    roughness: 0.2,
    metalness: 0.8,
    flatShading: true,
  });
  return new THREE.Mesh(sphereGeometry, sphereMaterial);
}

onMounted(() => {
  console.log(`three-tile v${tt.version} start!`);

  // 创建地图
  const map = tt.TileMap.create({
    imgSource: new tt.plugin.ArcGisSource(),
    demSource: new tt.plugin.ArcGisDemSource(),
  });

  // 地图旋转到xz平面
  map.rotateX(-Math.PI / 2);

  // 初始化场景
  const viewer = new tt.plugin.GLViewer("#map");

  // 地图添加到场景
  viewer.scene.add(map);

  // 青岛中心位置
  const centerPosition = map.geo2world(new THREE.Vector3(120.3826, 36.0671, 0));
  const cameraPosition = map.geo2world(new THREE.Vector3(120.3826, 36.0571, 0.9));

  // 飞行到目标位置
  viewer.flyTo(centerPosition, cameraPosition);

  // 添加红色立方体
  const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1);
  const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
  const cube = new THREE.Mesh(geometry, material);
  cube.position.copy(map.geo2world(new THREE.Vector3(120.3826, 36.0671, 0.5)));
  viewer.scene.add(cube);

  // 添加绿色球体
  const lonlat1 = new THREE.Vector3(120.32, 36.08, 1);
  const sphere1 = createSphere(0x00ff00);
  sphere1.position.copy(map.geo2world(lonlat1));
  viewer.scene.add(sphere1);

  // 限制相机高度,防止进入地下
  viewer.addEventListener("update", () => {
    tt.plugin.limitCameraHeight(map, viewer.camera);
  });
});
</script>

<style scoped>
html, body {
  background-color: #333;
  height: 400px;
  width: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  overflow: hidden;
}

#map {
  flex: 1;
}
</style>

2. 主要功能解析

  1. 创建地图:使用 three-tile 提供的 TileMap.create 方法加载 ArcGis 影像源和地形数据源。
  2. 相机定位:通过 geo2world 将经纬度转换为 Three.js 世界坐标。
  3. 添加几何体:在地理上空添加立方体和球体。
  4. 相机高度限制:防止相机进入地下。

3. 效果展示

  • 红色立方体悬浮在地理上空
  • 绿色球体位于指定的经纬度位置

4. 总结

通过 Three.js + Three-Tile,成功地在地理位置上渲染了三维地形,并添加了几何体。


5. 参考文档