1.实现效果
2.代码
1.npm安装three.js
npm install three
2.引入three.js
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
3.初始化模型
init(val) {this.container = document.querySelector('.container')// 初始场景this.scene = new THREE.Scene()// 初始化相机this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)// 相机位置this.camera.position.z = 5// 初始化渲染器this.renderer = new THREE.WebGLRenderer()this.renderer.setSize(window.innerWidth, window.innerHeight)// 添加球体方式一:对于.hdr图片// 添加球体方式二:对于.jpg .png图片const geometry = new THREE.SphereGeometry(5, 32, 32)const meterial = new THREE.MeshBasicMaterial()// 这里图片的地址val默认位置在public文件下方,所以测试的图片直接添加在public文件夹内部即可,val格式'./images/demo1.jpg'let texture = new THREE.TextureLoader().load(val)meterial.map = texturethis.sphere = new THREE.Mesh(geometry, meterial)// 改变视角,进入球体内部this.sphere.geometry.scale(1, 1, -1)this.scene.add(this.sphere)// 添加控制器,控制视角const controls = new OrbitControls(this.camera, this.container)// controls.enableDamping = true// 容器上面添加渲染器this.container.appendChild(this.renderer.domElement)// 逐帧渲染const circleRender = () => {this.renderer.render(this.scene, this.camera)requestAnimationFrame(circleRender)}circleRender()},
4.展示结束销毁模型
disposeThreeJS() {if (this.renderer) {this.renderer.domElement.remove(); // 从DOM中移除渲染器元素this.renderer.dispose();}if (this.sphere && this.sphere.geometry) {this.sphere.geometry.dispose();}if (this.sphere && this.sphere.material) {this.sphere.material.dispose();}if (this.controls) {// OrbitControls没有直接的dispose方法,但可以通过设置引用为null来释放它this.controls.dispose = () => { }; // 假设你有一个空方法来标记它已被“处理”this.controls = null;}// 注意:场景和相机通常不需要显式销毁,除非你有大量的资源需要清理// 但为了完整性,你可以将它们设置为nullthis.scene = null;this.camera = null;},
5.测试图片