基于Threejs实现glb三维模型的预览

43 篇文章 4 订阅
41 篇文章 6 订阅

本文重点介绍如何基于Threejs对glb三维模型进行预览,关于threejs和三维建模等不在本文讨论之内,想详细了解threejs和glb三维模型的,请自行百度学习。

言归正传,使用threejs进行三维模型展示,通常需要依赖以下组件:

Threejs+OrbitControls+GLTFLoader+WebGL

以上组件可以从threejs的官网获取,下载后的目录如下所示:

第一步、创建html,引入相关的js资源,代码如下:

<html lang="en">
	<head>
		<title>3D模型实时观看</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			body {
				font-family: Monospace;
				background-color: #fff;
				color: black;
				margin: 0px;
				overflow: hidden;
			}
 
			#modelBorderContainer{
				display: flex;
				justify-content: center;
				align-items: center;
				position: absolute;
				width: 100%;
				height: 100%;              
			}
			#modelBorder {
				max-width: 512px;
				width: 100%;
				height: 50%;
			}
            canvas{
                position: absolute;
                top: 0%;
                left: 0%;
            }
		</style>
	</head>
 
	<body>
		<div id="modelBorderContainer">
			<div id="modelBorder"></div>
		</div>
		<script type="application/javascript">
			var modelUrl = 'models/Cesium_Air.glb';     //定义所使用模型路径
		</script>
		<script src="lib/three.min.js?v=2.0.3"></script>
		<script src="lib/OrbitControls.js?v=2.0.3"></script>
		<script src="lib/GLTFLoader.js?v=2.0.3"></script>
		<script src="lib/WebGL.js?v=2.0.3"></script>
		<script src="lib/stats.min.js?v=2.0.3"></script>
		<script src="lib/3dmodel.js?v=2.0.3"></script>
	</body>
</html>

第二步、在3dmodel.js 中定义如何基于threejs进行加载。

1、创建三维预览需要的相机、场景、灯光等信息

function init() {
    if (!modelUrl) {
        return false;
    }
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    scene = new THREE.Scene();
    bbox = new THREE.Box3();

    scene.background = new THREE.Color( 0xeeeeee );
    light = new THREE.HemisphereLight( 0xbbbbff, 0x444422, 1.5 );
    light.position.set( 0, 1, 0 );
    scene.add( light );
    var loader = new THREE.GLTFLoader();

    loader.load( modelUrl, function ( gltf ) {
        gltf.scene.name = '3dmodel';
        this.setContent(gltf.scene);
        
        scene.add( gltf.scene );
    }, undefined, function ( e ) {
        console.error( e );
    } );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setPixelRatio( window.devicePixelRatio );

    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.gammaOutput = true;
    container.appendChild( renderer.domElement );
    window.addEventListener( 'resize', onWindowResize, false );

    camera = new THREE.PerspectiveCamera(45,window.innerWidth / window.innerHeight,	0.01,1000);

    controls = new THREE.OrbitControls(camera);
    // to disable pan
    controls.enablePan = false;
    // to disable zoom
    //controls.enableZoom = false;
	controls.enableZoom = true;
    controls.target.set(0,0,0);
    controls.update();
}

2、定义模型的旋转运动和事件监听

function animate() {
    requestAnimationFrame( animate );
    if (rotating) {
        scene.rotation.y += -0.005;
    } else {
        scene.rotation.y = scene.rotation.y;
    }

    renderer.render( scene, camera );
}

function pauseRotation() {
    var modelBorder = document.getElementById("modelBorder");
    modelBorder.addEventListener("mouseenter", function( event ) {
        rotating = false;
    });
    modelBorder.addEventListener("mouseleave", function( event ) {
        rotating = true;
    });
    modelBorder.addEventListener('touchmove', function(e) {
        rotating = false;
    }, false);
    modelBorder.addEventListener('touchstart', function(e) {
        rotating = false;
    }, false);
    modelBorder.addEventListener('touchend', function(e) {
        rotating = true;
    }, false);

}

3、定义加载模型的参数

function setContent(object) {
    object.updateMatrixWorld();

    const box = new THREE.Box3().setFromObject(object);
    const size = box.getSize(new THREE.Vector3()).length();
    const boxSize = box.getSize();
    const center = box.getCenter(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;

    this.camera.position.copy(center);
    if (boxSize.x > boxSize.y) {
        this.camera.position.z = boxSize.x * -2.85
    } else {
        this.camera.position.z = boxSize.y * -2.85
    }
    this.camera.lookAt(0, 0, 0);
}

将编辑好的代码发布至nginx后,可以看到以下的效果。

切换其它模型,如飞机等:

通过本文可实现三维Glb模型的预览,目前还存在一点问题,比如支持的格式限于glb,对于gltf或者3dmax的模型不支持。

上述代码可在码云上下载:https://gitee.com/yelangcode/threejs_model_view,有兴趣的朋友可自行fork。

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜郎king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值