练习一堆彩色三角形
- cube.js
import * as THREE from "three";
export function createMesh() {
const meshs = [];
for (let i = 0; i < 50; i++) {
const geometry = new THREE.BufferGeometry();
const positionArray = new Float32Array(9);
for (let j = 0; j < 9; j++) {
positionArray[j] = Math.random() * 10 - 5;
}
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positionArray, 3)
);
// 生成随机颜色
let color = new THREE.Color(Math.random(), Math.random(), Math.random());
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.5,
});
// 创建物体
const mesh = new THREE.Mesh(geometry, material);
meshs.push(mesh);
}
return meshs;
}
- main.js
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 导入动画库
// 导入dat.gui库
import { createMesh } from "./cube";
// 目标js控制画面全屏
// 1. 创建场景
const scene = new THREE.Scene();
// 2.创建一个(透视)相机对象 角度75° 屏幕的宽高比
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1, //近端
1000 //远端的景深
);
// 3.设置相机位置
camera.position.set(0, 0, 10); // x y z坐标
// 4.添加到场景当中
scene.add(camera);
// 5.添加物体
const meshs = createMesh();
meshs.forEach((mesh) => {
scene.add(mesh);
});
// 6.初始化渲染器(进行渲染)
const renderer = new THREE.WebGLRenderer();
// 6.1 设置渲染的尺寸大小(这里根据屏幕的尺寸大小进行渲染)
renderer.setSize(window.innerWidth, window.innerHeight);
// 7.渲染的东西(渲染是往canvas上面去画的)添加到元素中(这里添加到body中)
document.body.appendChild(renderer.domElement); //这个是canvas
// 9.显示3维立体的图形(轨道控制器)
// 9.1 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement); //相机 和 监控的对象
// 9.2 --- 设置控制器的阻尼 ---
controls.enableDamping = true; //必须在动画循环中.update()
// 10. 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 设置一个渲染函数
function render() {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(render); //动画帧->渲染下一帧
}
render();
// 监听画面的变化,更新渲染画面
window.addEventListener("resize", () => {
console.log("画面变化了");
// 更新摄像机
camera.aspect = window.innerWidth / window.innerHeight; //宽高比
// 更新摄像机的投影景深
camera.updateProjectionMatrix();
// 更新渲染器的范围
renderer.setSize(window.innerWidth, window.innerHeight);
// 如果屏幕像素比变化了 -> 需要设置渲染器像素比
renderer.setPixelRatio(window.devicePixelRatio);
});
- 效果如下图: