今天先完成一个模型在网页中的渲染
1.准备工作 安装下载three依赖
2.创建新的文件模块存放模型
3.试运行下方代码尝试了解 模型渲染的基本要素 场景 相机 光源
dom部分
<template>
<div id="container"></div>
</template>
引入依赖
import { onMounted } from "vue";
// 引入three
import * as THREE from "three";
// 引入轨道控制器扩展库OrbitControls.js
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
模型创建
// 创建一个三位场景
const scene = new THREE.Scene();
//创建一个长方体几何对象Geometry
const geometry = new THREE.BoxGeometry(50, 50, 50);
//创建一个材质对象Material
const material = new THREE.MeshLambertMaterial({
color: "#0ff",
transparent: true, //开启透明
opacity: 0.5, //设置透明度
});
const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
//设置网格模型在三维空间中的位置坐标,默认是坐标原点
mesh.position.set(0, 10, 0);
//网格模型mesh添加到三维场景
scene.add(mesh);
// AxesHelper:辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
scene.add(axesHelper);
//环境光:没有特定方向,整体改变场景的光照明暗
const ambient = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambient);
// 定义相机输出画布的尺寸(单位:像素px)
const width = 800; //宽度
const height = 500; //高度
// 实例化一个透视投影相机对象 -----模拟人眼
// 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000:远裁截面
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
//相机在Three.js三维坐标系中的位置
camera.position.set(200, 200, 200);
camera.lookAt(mesh.position); //指向mesh对应的位置
// 创建渲染器对象
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
renderer.render(scene, camera); //执行渲染操作
//渲染节点
onMounted(() => {
const container = document.getElementById("container");
container?.appendChild(renderer.domElement);
});
样式参考
<style scoped>
#container {
display: flex;
justify-content: center;
height: 800px;
}
.ui {
position: relative;
bottom: 59%;
left: 50%;
color: red;
z-index: 2;
}
</style>