Three.js+vue3+vite生成基础场景
框架:vue3+vite+typescript
代码如下(示例):
//js引入
npm install three
//ts引入
npm install @types/three
three.js的场景就相当于居住的房子,所有的元素都包含在其中
//创建场景
scene = new THREE.Scene();
我们所看到的three.js创建的内容都是通过相机观察到的
//添加相机
const initCamera = () => {
//创建相机
camera = new THREE.PerspectiveCamera(
50,
width / height,
0.1,//相机近点
3200//相机远点
);
//相机定位
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 0;
camera.lookAt(scene.position);//锁定场景
}
要让three.js在页面上呈现出来,我们需要创建一个容器,在容器中将我们搭建的场景展现出来
//获取容器信息
const getCanvas=()=>{
//获取容器及宽高
canvas = document.getElementById("container");
width=canvas.clientWidth;
height=canvas.clientHeight;
}
//初始化渲染器
const initRender = () => {
//渲染器定义
renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);//渲染大小
renderer.setClearColor(0x2FFFFF, 1.0);//渲染颜色
renderer.render(scene, camera);
canvas.appendChild(renderer.domElement);//加入容器
}
废话说完,代码奉上
<template>
<div id="container"></div>
</template>
<script setup lang="ts">
import * as THREE from 'three';
import {onMounted} from "vue";
onMounted(() => {
init();
})
let scene: any = '',
camera: any = '',
canvas: any = '',
renderer: any = '',
width: number = 0,
height: number = 0;
//初始化
const init = () => {
//创建场景
scene = new THREE.Scene();
getCanvas();
initCamera();
initRender();
}
const getCanvas=()=>{
//获取容器及宽高
canvas = document.getElementById("container");
width=canvas.clientWidth;
height=canvas.clientHeight;
}
//添加相机
const initCamera = () => {
//创建相机
camera = new THREE.PerspectiveCamera(
50,
width / height,
0.1,//相机近点
3200//相机远点
);
//相机定位
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 0;
camera.lookAt(scene.position);//锁定场景
}
//初始化渲染器
const initRender = () => {
//渲染器定义
renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);//渲染大小
renderer.setClearColor(0x2FFFFF, 1.0);//渲染颜色
renderer.render(scene, camera);
canvas.appendChild(renderer.domElement);//加入容器中
}
</script>
<style lang="scss" scoped>
#container {
width: 100%;
height: 100%;
}
</style>