<div id="container"></div>
import * as Three from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import axios from 'axios'
//获取商品详情
data(){
return {
camera: null,
renderer: null,
mesh: null,
}
}
getGoodsInfo(goodsID) {
goodsInfo({goodsID:goodsID},(res) => {
this.goodsInfoData = res
if (res.worksType==4){
//three.js
this.init()
this.animate()
}, (err) => { console.log(err) })
},
// three.js
init() {
const container = document.getElementById('container')
this.camera = new Three.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 10000)
this.renderer = new Three.WebGLRenderer({ antialias: true })
this.scene = new Three.Scene()
this.scene.position.y = -(container.clientHeight/2)
this.camera.position.set(180, 180, 600)
this.camera.up.set(0, 1, 0)
this.camera.lookAt({ x: 0, y: 0, z: 0 });
this.renderer.setSize(container.clientWidth, container.clientHeight)
this.renderer.shadowMap.enabled = true
container.appendChild(this.renderer.domElement)
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
this.controls.target = new Three.Vector3(0, 0, 0)
this.loadLight()
this.load3D()
this.setModelPosition(this.scene)
},
setModelPosition(object) {
object.updateMatrixWorld();
// 获得包围盒得min和max
const box = new Three.Box3().setFromObject(object);
// 返回包围盒的宽度,高度,和深度
// 返回包围盒的中心点
const center = box.getCenter(new Three.Vector3());
const size = box.getSize(new Three.Vector3());
// object.position.x += object.position.x - center.x;
// object.position.y += object.position.y - center.y;
// object.position.z += object.position.z - center.z;
},
load3D() {
const loader = new GLTFLoader()
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('/draco/')
dracoLoader.preload()
loader.setDRACOLoader(dracoLoader)
//获取文件流
axios.get(this.goodsInfoData.worksUrlOss, {
responseType: 'blob'
}).then(res => {
if(res.status==200){
let blob = new Blob([res.data])
let modelUrl = window.URL.createObjectURL(blob);
//文件流转本地url
//如需加载本地文件,直接放在public下(只能放在public)
loader.load(modelUrl, (gltf) => {
this.scene.add(gltf.scene)
this.renderer.render(this.scene, this.camera)
}, (xhr) => {
//这边可以获取到加载进度,可在加载之前进行操作
// console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
}, (error) => {
console.error(error)
})
}else{
}
})
},
loadLight() {
// 点光源
const point = new Three.PointLight(0xffffff)
point.position.set(4000, 4000, 4000) // 点光源位置
this.scene.add(point) // 点光源添加到场景中
// 环境光
const ambient = new Three.AmbientLight(0xFFFFFF)
this.scene.add(ambient)
},
animate() {
requestAnimationFrame(this.animate)
this.renderer.render(this.scene, this.camera)
},
|