<!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';
//引入性能监视器stats.js
import Stats from 'three/addons/libs/stats.module.js';
// 画布尺寸
const width = window.innerWidth;
const height = window.innerHeight;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000); // 视场角度fov; 画布宽高比; 近裁截面; 远裁截面
const renderer = new THREE.WebGLRenderer();
const geometry = new THREE.BoxGeometry(100, 100, 100); // 形状
const material = new THREE.MeshLambertMaterial({
color: '#fff',
transparent: true,
opacity: 0.6
}); // 材质(分为是否受光照影响)
const mesh = new THREE.Mesh(geometry, material); // 网格模型
const axesHelper = new THREE.AxesHelper(150); // 坐标系
const pointLight = new THREE.DirectionalLight('blue', 1); // 光源
const pointLightHelper = new THREE.PointLightHelper(pointLight, 10); // 光源辅助观察
const controls = new OrbitControls(camera, renderer.domElement); // 相机控件轨道控制器
const stats = new Stats(); // 性能监视器
pointLight.decay = 0.0; // 设置光源不随距离衰减,默认为2.0
pointLight.position.set(-500, 400, 500);
mesh.position.set(200, 100, 100);
scene.add(mesh);
scene.add(axesHelper);
scene.add(pointLight);
scene.add(pointLightHelper);
camera.position.set(-300, 200, 200); // x,y,z
camera.lookAt(mesh.position); // 相机视角: 指向mesh设置的位置(中心点)
renderer.setSize(width, height);
renderer.render(scene, camera); // 执行渲染操作
document.body.appendChild(renderer.domElement); // 通过.domElement获得.render渲染方法生成的canvas画布
document.body.appendChild(stats.domElement);
// 随机创建大量的模型,测试渲染性能
// const num = 20000; //控制长方体模型数量
// for (let i = 0; i < num; i++) {
// const geometry = new THREE.BoxGeometry(5, 5, 5);
// const material = new THREE.MeshLambertMaterial({
// color: 0x00ffff
// });
// const mesh = new THREE.Mesh(geometry, material);
// // 随机生成长方体xyz坐标
// const x = (Math.random() - 0.5) * 200
// const y = (Math.random() - 0.5) * 200
// const z = (Math.random() - 0.5) * 200
// mesh.position.set(x, y, z)
// scene.add(mesh); // 模型对象插入场景中
// }
window.onresize = () => {
const newWidth = window.innerWidth;
const newHeight = window.innerHeight;
renderer.setSize(newWidth, newHeight); // 更新渲染器尺寸
camera.aspect = newWidth / newHeight; // 更新相机比例
camera.updateProjectionMatrix(); // 如果相机的一些属性发生了变化,需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
}
/**
旋转:拖动鼠标左键
缩放:滚动鼠标中键
平移:拖动鼠标右键
设置了渲染循环,相机控件OrbitControls就不用再通过事件监听
*/
// controls.addEventListener('change', () => {
// renderer.render(scene, camera);
// // console.log('camera.position',camera.position);
// })
const render = () => {
stats.update();
renderer.render(scene, camera);
mesh.rotateY(0.01);
requestAnimationFrame(render); // 实现周期性循环执行;默认每秒钟执行60次,但不一定能做到,要看代码的性能.
}
render()
{
"dependencies": {
"three": "0.173.0"
}
}
预览