threejs
threejs用于实现3D效果
vite创建vuejs项目
npm create vite
选择vue 和js创建vue3项目
安装threejs
npm install three
运行项目
cd project
npm i
npm run dev
修改App.vue
创建一个场景和立方体(Creating a scene)
<script setup>
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 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 cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
</script>
<template>
</template>
<style scoped>
</style>
显示如图:
载入3D模型
可以到这个网站下载3D模型
推荐下载glTF格式,解压到项目中
<script setup>
import * as THREE from 'three'; // 全局引入
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(0, 0, 500);
camera.lookAt(100, 0, 0);
const scene = new THREE.Scene();
const loader = new GLTFLoader();
loader.load('src/model/scene.gltf', function (gltf) {
scene.add(gltf.scene);
renderer.render(scene, camera);
}, function (ProgressEvent) {
console.log(ProgressEvent);
}, function (error) {
console.error(error);
});
</script>
<template>
</template>
<style scoped>
</style>
添加轨道控制器(OrbitControls)
Orbit controls(轨道控制器)可以使得相机围绕目标进行轨道运动。
需要import OrbitControls
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
App.js
<script setup>
import * as THREE from 'three'; // 全局引入
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 500);
camera.lookAt(100, 0, 0);
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();
const loader = new GLTFLoader();
loader.load('src/model/scene.gltf', function (gltf) {
scene.add(gltf.scene);
function animate() {
requestAnimationFrame(animate);
// required if controls.enableDamping or controls.autoRotate are set to true
controls.update();
renderer.render(scene, camera);
}
animate()
}, function (ProgressEvent) {
console.log(ProgressEvent);
}, function (error) {
console.error(error);
});
</script>
<template>
</template>
<style scoped>
</style>