网上有很多uniapp使用tree.js的教程,但是我在使用测试中,发现tree.js的官方3d模型中有很多加载不出来,但是也没有报错,全网搜也没搜到方法,最后发现是缩放的问题,这里将代码贴出来,关键的方法是getfitscalevalue()这个方法
<template>
<view id="app">
<canvas id="webgl" ref="webgl" canvas-id="webgl" type="webgl"
:style="'width:'+mscenewidth+'px; height:'+msceneheight+'px;'">
</canvas>
</view>
</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';
import {
fbxloader
} from 'three/examples/jsm/loaders/fbxloader.js';
import {
dracoloader
} from "three/examples/jsm/loaders/dracoloader.js";
import {
objloader
} from "three/examples/jsm/loaders/objloader.js";
export default {
//soldier
data() {
return {
mscenewidth: 0, // 手机屏幕宽度
msceneheight: 0, // 手机屏幕高度
canvas: null,
worldfocus: null, // 世界焦点(模型放置,相机围绕的中心)
renderer: null,
mcanvasid: null,
scene: null,
mesh: null,
camera: null,
clock: null,
renderanimframeid: null, // 渲染帧动画id
controls: null,
times: 0,
changeflag: true,
mixer: null,
previoustime: 0,
modelurl: "/static/soldier.glb"
};
},
mounted() {
// uni.createselectorquery().in(this).select('#webgl').fields({
// node: true
// }).exec(res=> {
// console.log(json.stringify(res))
// this.mcanvasid = res[0].node.id;
// // 注册画布
// const mcanvas = three.global.registercanvas(this.mcanvasid, res[0].node);
// // 开始初始化
// this.init(mcanvas);
// })
},
// 页面加载时
onload(option) {
// 获取手机屏幕宽高
this.mscenewidth = uni.getwindowinfo().windowwidth;
this.msceneheight = uni.getwindowinfo().windowheight;
// 设置世界中心
this.worldfocus = new three.vector3(0, 0, 0);
},
// 页面加载完毕后
onready() {
this.init()
},
onshow() {
},
onhide() {
this.disposes()
cancelanimationframe(this.animate())
},
methods: {
// 在不需要时释放资源
disposes() {
// 释放几何体
this.scene.traverse((object) => {
if (object.geometry) {
object.geometry.dispose();
}
// 释放材质
if (object.material) {
if (array.isarray(object.material)) {
object.material.foreach(material => material.dispose());
} else {
object.material.dispose();
}
}
});
// 释放渲染器
if (this.renderer) {
this.renderer.dispose();
}
// 清除场景
while (this.scene.children.length > 0) {
this.scene.remove(this.scene.children[0]);
}
},
getfitscalevalue(scene) {
let box=new three.boxgeometry(3,3,3)
let mail=new three.meshbasicmaterial({color:0xff6600})
let mesh=new three.mesh(box,mail)
var boxes = new three.box3().setfromobject( scene );
var maxdiameter = math.max((boxes.max.x - boxes.min.x), (boxes.max.y - boxes.min.y), (boxes.max.z - boxes.min.z)); //数值越大,模型越小
console.log(maxdiameter)
return math.ceil(this.msceneheight / maxdiameter/4);
},
init() {
// 创建一个场景
this.scene = new three.scene()
//三位坐标线
// const axeshelper = new three.axeshelper(5);
// this.scene.add(axeshelper);
//创建相机对象,45是相机的视角 , 宽高比是屏幕的宽高比 , 最近能看到0.1 , 最远能看到10000
// this.camera = new three.orthographiccamera(-s * k, s * k, s , -s, 1, 1000);
// this.camera.position.set(0, 20, 300);
const lod = new three.lod();
// 创建不同细节级别的几何体
const highdetailgeometry = new three.boxgeometry(1, 1, 1);
const mediumdetailgeometry = new three.boxgeometry(0.5, 0.5, 0.5);
const lowdetailgeometry = new three.boxgeometry(0.25, 0.25, 0.25);
// 创建材质
const material = new three.meshbasicmaterial({
color: 0xff0000
});
// 创建不同细节级别的网格
const highdetailmesh = new three.mesh(highdetailgeometry, material);
const mediumdetailmesh = new three.mesh(mediumdetailgeometry, material);
const lowdetailmesh = new three.mesh(lowdetailgeometry, material);
// 将不同细节级别的网格添加到lod对象中
lod.addlevel(highdetailmesh, 0); // 距离0
lod.addlevel(mediumdetailmesh, 5); // 距离5
lod.addlevel(lowdetailmesh, 10); // 距离10
this.scene.add(lod);
this.camera = new three.perspectivecamera(75, this.mscenewidth / this.msceneheight, 0.1, 2000);
//100,300 ,500
this.camera.position.set(0, 0, 5); //设置相机位置
//this.camera.position.set(100, -800, 500);
this.scene.add(this.camera)
this.camera.lookat(this.scene.position); //设置相机方向(指向的场景对象)
// 执行一个渲染函数
this.rendererglr()
/* 光源设置*/
this.pointlight()
this.clock = new three.clock()
//创建控件对象
this.change()
//更新轨道控件
let filename = this.modelurl.lastindexof(".")
let fileformat = this.modelurl.substring(filename + 1, this.modelurl.length).tolowercase()
if (fileformat == 'fbx') {
this.fbxloader()
} else if (fileformat == 'glb') {
this.gblloader()
} else if (fileformat == 'obj') {
this.objloader()
}
//this.renderer.render(this.scene, this.camera);
},
pointlight() {
let ambientlight = new three.ambientlight(0xffffff, 1);
this.scene.add(ambientlight);
const directional_light = new three.directionallight(0xffffff, 1);
directional_light.position.set(0, 1, 0);
directional_light.castshadow = true;
this.scene.add(directional_light);
let a = 1,
b = 0.6,
c = 10;
let directionallight1 = new three.directionallight(0xffffff, b);
directionallight1.position.set(-a, -a, a * c).normalize();
let directionallight2 = new three.directionallight(0xffffff, b);
directionallight2.position.set(a, -a, -a * c).normalize();
let directionallight3 = new three.directionallight(0xffffff, b);
directionallight3.position.set(-a, a, -a * c).normalize();
let directionallight4 = new three.directionallight(0xffffff, b);
directionallight4.position.set(a, a, a * c).normalize();
this.scene.add(directionallight1);
this.scene.add(directionallight2);
this.scene.add(directionallight3);
this.scene.add(directionallight4);
},
//渲染函数
rendererglr() {
this.$nexttick(() => {
const element = document.getelementbyid('webgl')
this.canvas = element
this.renderer.setsize(element.clientwidth, element.clientheight);
element.appendchild(this.renderer.domelement);
})
this.renderer = new three.webglrenderer({
alpha: true,
antialias: true,
powerpreference: "high-performance",
precision: "mediump"
}); //alpha:true背景透明
this.renderer.setpixelratio(window.devicepixelratio * 2);
this.renderer.tonemapping = three.acesfilmictonemapping;
this.renderer.tonemappingexposure = 1.0;
this.renderer.outputcolorspace = three.srgbcolorspace;
this.renderer.shadowmap.enabled = true;
this.renderer.shadowmap.type = three.pcfsoftshadowmap;
},
//创建控件对象
change() {
this.controls = new orbitcontrols(this.camera, this.renderer.domelement);
this.controls.mindistance = 300
this.controls.maxdistance = 1000
this.controls.addeventlistener('change', () => {
this.renderer.render(this.scene, this.camera);
}); //监听鼠标、键盘事件
//禁止缩放
this.controls.enablezoom = this.changeflag
//禁止旋转
this.controls.enablerotate = this.changeflag
//禁止右键拖拽
this.controls.enablepan = this.changeflag
},
//更新轨道控件
animate() {
if (this.renderer) {
// console.log(this.stats)
// this.stats.update()
let t = this.clock.getdelta()
let rendert = 1 / 30
this.times = this.times + t
if (this.times > rendert) {
this.controls.update();
this.renderer.render(this.scene, this.camera);
this.times = 0
}
requestanimationframe(this.animate);
if (!this.changeflag) {
this.controls.autorotatespeed = 16
}
this.controls.autorotate = false // 是否自动旋转
}
//创建一个时钟对象
//this.clock = new three.clock()
//this.scene.rotatey(0.01)
//获得两帧的时间间隔 更新混合器相关的时间
if (this.mixer) {
this.mixer.update(this.clock.getdelta()*100)
}
},
objloader() {
let that = this
const loader = new objloader();
uni.showloading({
title: "正在加载"
})
// load a resource
loader.load(
// resource url
that.modelurl,
// called when resource is loaded
function(object) {
console.log(object)
uni.hideloading()
var scale = that.getfitscalevalue(object)
console.log(scale)
object.scale.set(scale, scale, scale);
that.scene.add(object);
settimeout(function() {
//that.renderer.render(that.scene, that.camera);
that.animate()
}, 1000);
},
// called when loading is in progress
function(xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
// called when loading has errors
function(error) {
console.log('an error happened');
}
);
},
//导入fbx模型文件
fbxloader() {
let that = this
const loader = new fbxloader();
loader.load(this.modelurl, function(mesh) {
that.scene.add(mesh);
that.ownerinstance.callmethod('onload')
})
},
//导入glb模型文件
gblloader() {
uni.showloading({
title: "正在加载",
})
let that = this
const loader = new gltfloader();
const dracoloader = new dracoloader();
dracoloader.setdecoderpath("/static/draco/");
loader.setdracoloader(dracoloader);
loader.load(that.modelurl, function(gltf) {
uni.hideloading()
//that.mesh = gltf.scene
if (gltf.animations.length > 0) {
that.mixer = new three.animationmixer(gltf.scene)
const action = that.mixer.clipaction(gltf.animations[0])
// 让动画进入播放状态
action.play()
}
var scale = that.getfitscalevalue(gltf.scene)
console.log(scale)
gltf.scene.scale.set(scale, scale, scale);
that.scene.add(gltf.scene);
settimeout(function() {
//that.renderer.render(that.scene, that.camera);
that.animate()
}, 1000);
}, function(xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, function(err) {
console.log(err)
});
},
// 触摸开始
// 触摸事件处理
ontouchstart(event) {
const touch = event.touches[0];
const rect = this.canvas.getboundingclientrect();
const x = touch.clientx - rect.left;
const y = touch.clienty - rect.top;
// 在这里处理触摸开始事件
},
ontouchmove(event) {
const touch = event.touches[0];
const rect = this.canvas.getboundingclientrect();
const x = touch.clientx - rect.left;
const y = touch.clienty - rect.top;
// 在这里处理触摸移动事件
},
ontouchend() {
// 在这里处理触摸结束事件
}
}
}
</script>
<style lang="scss">
</style>未调用缩放方法,就是空白,调用后:

到此这篇关于uniapp 使用 tree.js 解决模型加载不出来的问题的文章就介绍到这了,更多相关uniapp tree.js 模型加载不出来内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论