<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
index.html
main.js
package.json
现在支持上传本地图片了!
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 引入gltf模型加载库GLTFLoader.js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 3000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
const axesHelper = new THREE.AxesHelper(150);
// 添加环境光
const ambientLight = new THREE.AmbientLight(0x404040, 2);
// 添加方向光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
// 添加点光源,红色的点光源
const pointLight = new THREE.PointLight(0xff0000, 2, 10);
// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
directionalLight.position.set(5, 5, 5).normalize();
directionalLight.castShadow = true; // 方向光投射阴影
pointLight.position.set(2, 2, 2);
pointLight.castShadow = true; // 点光源投射阴影
controls.enableDamping = true; // 启用阻尼效果
controls.dampingFactor = 0.05; // 阻尼系数
scene.add(axesHelper);
scene.add(directionalLight);
scene.add(ambientLight);
scene.add(pointLight);
// 设置相机位置
camera.position.set(300, 100, 600);
camera.lookAt(0, 0, 0);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // 启用阴影
renderer.setClearColor(0x444444, 1);
document.body.appendChild(renderer.domElement);
// 创建GLTF加载器对象
const loader = new GLTFLoader();
// loader.load(模型路径,加载完成函数,加载过程函数) 可以添加模型加载进度条
// 使用Three.js官方提供的CDN链接来加载GLTF模型
loader.load('https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/2CylinderEngine/glTF/2CylinderEngine.gltf', (gltf) => {
console.log("创建加载器对象");
// 批量修改gltf的材质
gltf.scene.traverse((obj) => {
if(obj.isMesh) { // 判断是否是网格模型
console.log('gltf默认材质',obj.material);
obj.material.transparent = true;
obj.material.opacity = 0.8;
}
});
// 返回的场景对象gltf.scene插入到threejs场景中
scene.add(gltf.scene);
})
const animate = () => {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
controls.addEventListener('change', () => {
renderer.render(scene, camera);
})
window.onresize = () => {
const newWidth = window.innerWidth;
const newHeight = window.innerHeight;
renderer.setSize(newWidth, newHeight); // 更新渲染器尺寸
camera.aspect = newWidth / newHeight; // 更新相机比例
camera.updateProjectionMatrix(); // 如果相机的一些属性发生了变化,需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
}
{
"dependencies": {
"three": "0.173.0"
}
}
预览