Vue(3.3.4)+three.js(0.161.0)实现3D可视化地图
<template>
<div id="container"></div>
</template>
<script>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export default {
name: 'ThreeJsMap',
mounted() {
this.init();
this.animate();
},
methods: {
init() {
const container = document.getElementById('container');
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, container.offsetWidth / container.offsetHeight, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(this.renderer.domElement);
this.camera.position.set(0, 10, 25);
this.addLights();
this.addMap();
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
window.addEventListener('resize', this.onWindowResize.bind(this), false);
},
addLights() {
const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight.position.set(1, 1, 1);
this.scene.add(directionalLight);
},
addMap() {
const loader = new GLTFLoader();
loader.load('models/map.gltf', (gltf) => {
gltf.scene.scale.set(0.01, 0.01, 0.01);
this.scene.add(gltf.scene);
});
},
animate() {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
this.controls.update();
},
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
}
};
</script>
<style>
#container {
width: 100vw;
height: 100vh;
overflow: hidden;
}
</style>
这段代码展示了如何在Vue组件中初始化Three.js场景,包括添加灯光、加载模型以及实现场景的动态渲染和响应式窗口缩放。这是一个很好的Three.js和Vue结合的入门示例。
评论已关闭