Three.js加载三维(.gbl)模型

Three.js加载三维(.gbl)模型

近期有个项目中需要实现在页面中加载出三维模型并有旋转的动画展示 ,毫无疑问,当谈到在Web上呈现引人入胜的三维体验时,Three.js是一个无可替代的工具。接下来就用three.js来简单的实现下加载三维模型的需求。

    1. 安装three.js
npm install three
    1. 创建场景
const planeBox = document.querySelector('.planeBox')!;
const {w, h} = getSize(planeBox);

const scene = new THREE.Scene();
    1. 创建相机
const camera = new THREE.PerspectiveCamera(45, w / h, 0.1, 20);
camera.position.set(0, 0, 1);
    1. 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(w, h);
planeBox.appendChild(renderer.domElement);
    1. 创建控制器
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.minDistance = 1;
controls.maxDistance = 10;
    1. 加载三维模型
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
	new GLTFLoader().load("/B2.glb", (gltf) => {
		gltfs = gltf;
		gltfs.scene.scale.set(0.02, 0.02, 0.02);
		gltfs.scene.position.set(0, 0, 0);
		gltfs.scene.rotation.x += 0.5;
		scene.add(gltfs.scene);
		animate();
	});
  • 7.动画函数
const animate = () => {
		loopId = requestAnimationFrame(animate);
		gltfs.scene.rotation.y -= 0.01;
		renderer.render(scene, camera);
	};
    1. 完整代码



    1. 展示效果

加载三维模型

你可能感兴趣的:(vue.js,three.js,3d)