three.js加载3D模型(.glb格式和.gltf格式)

要使用three.js实现在网页中加载3D模型进行实时展示的功能,首先要了解three.js

什么是three.js,Three.js是一款开源的主流3D绘图JS引擎,简单点,可以将它理解为three+js就可以了,three表示3D,js表示JavaScript的意思。那么合起来,three.js就是使用JavaScript脚本语言来写3D程序的意思。

使用three.js可以创建你想要的3D模型,然而我们通常想要快速用到的模型都是相对复杂的,那么使用three.js进行3D建模往往是困难而且不切实际的。所以我们可以直接选择现有的3D模型使用three.js导入并进行显示。

一、目录结构

将模型文件放入对于models文件夹中,也可以使用网络资源文件。

二、具体实现

index.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/source/Blue And White Porcelain 12th century by Mark_Energy.glb'     //定义所使用模型路径
		</script>
		<script src="js/three.min.js?v=2.0.3"></script>
		<script src="js/OrbitControls.js?v=2.0.3"></script>
		<script src="js/GLTFLoader.js?v=2.0.3"></script>
		<script src="js/WebGL.js?v=2.0.3"></script>
		<script src="js/stats.min.js?v=2.0.3"></script>
		<script src="js/3dmodel.js?v=2.0.3"></script>
	</body>
</html>

其中除过引入的导入模型的库文件以外,使用three.js实现对应场景,相机以及渲染器等内容,这里我定义为3dmodel.js

//3dmodel.js
if ( WEBGL.isWebGLAvailable() === false ) {
    document.body.appendChild( WEBGL.getWebGLErrorMessage() );
}
var container, stats, controls;
var camera, scene, renderer, light, bbox;
var rotating = true;

init();
animate();

pauseRotation();

function init() {
    if (!modelUrl) {
        return false;
    }
    container = document.createElement( 'div' );
    document.body.appendChild( container );    //创建div,并加载到html里,这里的document.body可以换成你想让模型加载的地方。

    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.target.set(0,0,0);
    controls.update();
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
}
//
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);

}

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);
}

其他js文件引入之后,在html中配置好模型路径之后,在3dmodel.js中修改相应参数达到自己想要的场景效果就可以得到一个可以在网页中实时展示的3d模型了。(本人也没有深入研究整个的渲染过程,只是有用到加载3D模型,所以也只能讲讲用法,不能细讲所有代码的实现过程,嘻嘻)

其他js文件下载地址:链接: https://pan.baidu.com/s/1HQ4nzaY-7qcHX_p0zwkfwQ 提取码: q6s6 复制这段内容后打开百度网盘手机App,操作更方便哦

注意:

在实现的过程中我有遇到一些问题,在Android端的微信中添加配置的3dmodel.js出现了所有其他点击事件失效的问题(没有其他功能单独展示3D模型可忽略),目前自己使用的解决方法有两种,一种是识别设备和环境,替换为图片,保证其他功能正常实现。第二种是将展示3D模型和其他功能分开实现,最终使用iframe再将3D模型展示嵌入到具备其他功能的网页中,但在多个模型加载中存在性能问题。

后续如果解决了再来更新,如果有人解决了希望也可以交流交流,万分感谢!

  • 25
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 38
    评论
评论 38
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值