import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
const scene = new THREE.Scene();
// 创建相机
// 实例化一个透视投影相机对象
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建几何体
const geometry = new THREE.BufferGeometry();
// 创建顶点数据 顶点是有顺序的 逆时针为正面
// 下边是一个三角形
//使用索引绘制 这是三个顶点 逆向是正面 顺向是反面 反面就要加上 side: THREE.DoubleSide
const vertices = new Float32Array([
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
]);
//三个为一组
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
// 创建材质
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
side: THREE.DoubleSide, //反面也能看到,
});
//创建一个网格
const plane = new THREE.Mesh(geometry, material);
//添加进场景里
scene.add(plane);
// 设置相机位置
camera.position.z = 5;
camera.position.y = 2;
camera.position.x = 2;
camera.lookAt(0, 0, 0);
// 添加世界坐标
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 添加轨道控制器
const controls = new OrbitControls(camera, document.body);
// 设置带阻尼的惯性
controls.enableDamping = true;
// 设置阻尼系数
controls.dampingFactor = 0.01;
// 自动旋转
controls.autoRotate = false;
//动画 自动执行
function animate() {
controls.update();
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
开看下效果吧
切记:创建顶点数据 顶点是有顺序的 逆时针为正面
wireframe: true,这个是展示线框的 设置在材质上 例如:
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
side: THREE.DoubleSide, //反面也能看到,
wireframe: true,//线框
});
这是效果 设置为true后 就不会展示平面 而是展示一个线框
若是要形成这样一个四边形 怎么写呢 就需要两个顶点
看下代码:
const vertices = new Float32Array([
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
]);
一个三角形是三个顶点 两个就是在加三个就OK了 但是这样的话 两个三角形组成一个面 一个面应该有四个顶点 现在却有六个 我们得简化下 让这两个共用一个顶点
就是使用索引绘制
//使用索引绘制
const vertices = new Float32Array([
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
// 1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
// -1.0, -1.0, 0.0,
]);
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
// 创建索引 根据顶点的索引
const indices = new Uint16Array([0, 1, 2, 2, 3, 0]);
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
言简意赅 就是共用了两个点 这就是顶点绘制