threejs官网:
https://threejs.org/
使用cdn引入threejs
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@v0.149.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@v0.149.0/examples/jsm/"
}
}
</script>
// 导入THREE和控制器
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 创建场景
const scene = new THREE.Scene();
// 设置背景色,16进制
// scene.background = new THREE.Color(0xffffff);
// 设置背景图片,需要6个图片,setPath为图片文件夹地址,load填写具体文件名,必须为正方形图片,否则报错
scene.background = new THREE.CubeTextureLoader().setPath('./img/').load(['5.png', '5.png', '5.png', '5.png', '5.png', '5.png'])
/**
添加雾,第一个参数为雾的颜色,
第二个参数为开始应用雾的最小距离,小于这个距离的物体不会受到影响;
第三个参数为应用雾的最大距离,大于这个距离的物体不会受到影响
**/
scene.fog = new THREE.Fog(0xffffff, 0, 80);
/**
创建透视相机,近大远小,类似人眼。
包含4个参数:
fov 角度,角度越大,看的越远,场景元素越小,使用滚轮操控相机控制器时放大缩小改变的是角度;
aspect 长宽比,默认窗口大小比,场景中的元素会根据此比例显示,如设置4 / 1,则元素会很扁
near 摄像机能看到最近的距离,相当于摄像机前面有一块透明的遮罩,只有遮罩前面的元素才能显示,遮罩后面的元素会被挡住,无法显示
far 摄像机能看到的最远的距离,相当于near遮罩前面还有一个遮罩,在near遮罩和这个遮罩里面的元素才能看见,超过far遮罩距离的元素无法看见
**/
const camera = new THREE.PerspectiveCamera();
// 移动相机位置
camera.position.z = 10;
camera.position.y = 5;
// 创建立方体,定义立方体结构和材质
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 颜色,16进制
// 创建网格,把立方体结构和材质添加进去,才能在页面上显示
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 3, 0) // 移动位置(x,y,z)
scene.add(cube);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
// 调整渲染器窗口大小
renderer.setSize(window.innerWidth, window.innerHeight);
// 把3d场景添加进页面中
document.getElementById('container').appendChild(renderer.domElement);
// 添加相机控制器,添加后可以拖动场景,鼠标滚轮放大缩小场景
const controls = new OrbitControls(camera, renderer.domElement);
// 监听轨道控制器修改事件,场景每次改变都会触发
controls.addEventListener('change', (e) => {
console.log('change controls');
});
// 添加阻尼效果,添加后,拖动场景场景会有一个惯性阻尼效果
controls.enableDamping = true;
controls.dampingFactor = 0.01; // 阻尼惯性
// 自动旋转,使场景自动旋转
controls.autoRotate = true;
controls.autoRotateSpeed = 0.5; // 旋转速度
// 添加坐标轴,辅助坐标轴,会显示x,y,z辅助线
const axesHelper = new THREE.AxesHelper(5);
axesHelper.position.y = 3
scene.add(axesHelper);
// 添加网格地面,辅助网格
const gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);
// 立方体动画
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
cube.rotation.z += 0.01;
// 移动相机,元素变化后更新相机位置
controls.update();
// 进行渲染,把场景和相机渲染出来
renderer.render(scene, camera);
}
animate();