nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 Mapbox (Part 2: Add a 3D model) #327

Open nonocast opened 1 week ago

nonocast commented 1 week ago

ref: Add a 3D model with threebox | Mapbox GL JS | Mapbox

yarn add three box-plugin

main.js

import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { Threebox } from 'threebox-plugin';

mapboxgl.accessToken = 'your-mapbox-token';

const map = new mapboxgl.Map({
  container: 'map', // container ID
  antialias: true,
  style: 'mapbox://styles/nonocast/cm0ttsm8t00m401rg3vk7ff4v',
  center: [121.5934326349772, 31.240585170245282],
  pitch: 60, // 俯仰角
  bearing: -65, // 旋转角
  zoom: 17
});

// eslint-disable-next-line no-undef
const tb = (window.tb = new Threebox(
  map,
  map.getCanvas().getContext('webgl'),
  {
      defaultLights: true
  }
));

map.on('style.load', () => {
  map.addLayer({
      id: 'custom-threebox-model',
      type: 'custom',
      renderingMode: '3d',
      onAdd: function () {
          const scale = 10;
          const options = {
              obj: 'house.glb',
              type: 'gltf',
              scale: { x: scale, y: scale, z: scale },
              units: 'meters',
              rotation: { x: 90, y: 0, z: 0 }
          };

          tb.loadObj(options, (model) => {
              model.setCoords([121.5934326349772, 31.240585170245282]);
              model.setRotation({ x: 0, y: 0, z: 70});
              tb.add(model);
          });
      },

      render: function () {
          tb.update();
      }
  });
});
Screenshot 2024-09-12 at 00 57 05

这样模型就混到map中去了,其中house.glb在#325中有描述。

然后把模型和地图对齐就会得到如下:

Screenshot 2024-09-12 at 01 17 08

收工。