引入ThreeJs
import * as THREE from "three";
创建三要素(场景、相机、渲染器)
// 创建场景
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.BoxGeometry(1,1,1);
创建父子材质
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const parentMaterial = new THREE.MeshBasicMaterial({color: '#e64a19'});
创建父子网格
const cube = new THREE.Mesh(geometry, material);
const parentCube = new THREE.Mesh(geometry, parentMaterial);
子网格嵌入到网格中并位移
parentCube.add(cube);
parentCube.position.set(2,0,0) // x y z
cube.position.set(3,1,0) // 相对于父cube移动
scene.add(parentCube);
效果图
完整代码
<template>
<div></div>
</template>
<script setup>
// 导入threejs
import * as THREE from "three";
// 创建场景
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.BoxGeometry(1,1,1);
// 创建材质
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const parentMaterial = new THREE.MeshBasicMaterial({color: '#e64a19'});
// 创建网格
const cube = new THREE.Mesh(geometry, material);
//++++++++++++++++++++++++++++++++++++++++++++++++++
const parentCube = new THREE.Mesh(geometry, parentMaterial);
parentCube.add(cube);
parentCube.position.set(2,0,0) // x y z
cube.position.set(3,1,0) // 相对于父cube移动
// 将网格添加到场景中
scene.add(parentCube);
//++++++++++++++++++++++++++++++++++++++++++++++++++
// 设置相机位置
camera.position.z = 5;
camera.lookAt(0,0,0);
// 添加轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const controls = new OrbitControls(camera ,renderer.domElement)
// 设置带阻尼的惯性
controls.enableDamping = true;
// 设置阻尼系数
controls.dampingFactor = 0.05;
// 添加坐标系
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 渲染函数
function animate() {
controls.update();
requestAnimationFrame(animate);
// 渲染
renderer.render(scene, camera);
}
animate();
</script>
<style>
*{
margin: 0;
padding: 0;
}
canvas {
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
}
</style>