Vue3+Three.js(一)

使用Three记住一下五点就能成功渲染模型了。

1、场景:创建场景 new THREE.Scene()

2、模型:创建几何模型/引入glb模型之类和创建材质 new THREE.MeshBasicMaterial()

3、渲染:renderer渲染器,顾名思义其负责渲染模型和场景到页面中

4、相机:camera 根据需求创建自己所需的相机类型,填写好各种参数,一般的视野角度75就够用了。

5、控制:controls负责控制页面旋转缩放操作的。

代码如下:
<script setup lang="ts">
import * as THREE from 'three';
import {onMounted, ref} from "vue";
import { ArcballControls} from "three/examples/jsm/controls/ArcballControls";

const containerRef = ref(null)
const width = ref()
const height = ref()
const animateKey = ref(false)
let cube, camera, renderer,scene;
onMounted(() => {
  width.value = containerRef.value.offsetWidth;
  height.value = containerRef.value.offsetHeight;
  initContainer()
})


const initContainer = () => {
  scene = new THREE.Scene(); // 创建场景
  camera = new THREE.PerspectiveCamera( 75, width.value / height.value, 0.1, 1000 );
  // fov:视野角度, aspect:长宽比,near近截面,far:远截面
  renderer = new THREE.WebGLRenderer();// 创建渲染器
  renderer.setSize( width.value , height.value ); // 设置渲染器尺寸
  containerRef.value.appendChild( renderer.domElement);
  const geometry = new THREE.BoxGeometry( 50, 50, 10 ); // 模型
  const material = new THREE.MeshBasicMaterial( { color: 0xff0033 } ); // 材质
  cube = new THREE.Mesh( geometry, material ); // 网格 需包含模型和材质

  // 控制器
  const controls = new ArcballControls( camera, renderer.domElement, scene );
  controls.addEventListener( 'change', function () {
    renderer.render( scene, camera );
  } );

  scene.add( cube ); // 像场景中添加模型
  camera.position.set( 0, 20, 100 );// 设置相机的位置
  controls.update();// 控制器
  animateKey.value = true
  // 因为animate自启动时页面还没加完成,所以加了个变量,当animateKey为true时才执行animate内的方法
  animate()
}

function animate() {
  if(animateKey.value) {
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
  }
}
animate()

</script>

<template>
  <div class="container" >
    <div class="container_canvas" ref="containerRef"></div>
  </div>
</template>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 1px solid red;
  .container_canvas {
    width: 80%;
    height: 80%;
  }
}
</style>
 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值