vue项目中使用three.js画一个几何体

本文介绍如何在Vue项目中引入Three.js库,并通过具体实例展示如何创建一个带有旋转立方体的3D场景。包括安装配置、场景初始化、相机设置、渲染器创建、几何体与材质定义及动画渲染等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明:事先安装three.js,npm install three --save    并将其绑定在vue上;在main.js中这样绑定;

import * as Three from 'three'
Vue.prototype.$THREE = Three

代码如下:

<template>
  <div  :style="{'maxHeight':maxHeight + 'px'}">
    <div id="demo"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      scene: null, // 场景对象
      camera: null, // 相机对象
      mesh: null, // 网格对象
      maxHeight: 500, //
      maxWidth: '100%' //
    };
  },
  mounted() {
    this.getTableHeight();
    this.initScene();
    this.initCamera();
    this.initRenderer();
    this.initGemotry();
    this.renderMethod();
  },
  methods: {
    getTableHeight() {
      var height = document.body.clientHeight - 230;
      this.maxHeight = height;
      this.maxWidth = window.innerWidth - 280;
    },
    // 初始化场景方法
    initScene() {
      this.scene = new this.$THREE.Scene();
    },
    // 初始化相机方法
    initCamera() {
      // 创建相机对象
      this.camera = new this.$THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
      this.camera.position.z = 10;
    },
    // 初始化渲染器的方法
    initRenderer() {
      this.renderer = new this.$THREE.WebGLRenderer();
      this.renderer.setSize(this.maxWidth, this.maxHeight);
      document.getElementById("demo").appendChild(this.renderer.domElement);
    },
    // 初始化立方体对象
    initGemotry() {
      var gemotry = new this.$THREE.BoxGeometry(4, 3, 3, 3, 3, 3); // 创建几何体
      var material = new this.$THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 创建材质
      this.mesh = new this.$THREE.Mesh(gemotry, material); // 创建网格
      this.scene.add(this.mesh); // 场景中添加网格
    },
    // 开始渲染
    renderMethod() {
      requestAnimationFrame(this.renderMethod);
      this.renderer.render(this.scene, this.camera);
      this.mesh.rotation.x += 0.01;
      this.mesh.rotation.y += 0.01;
    }
  }
};
</script>
<style lang="scss" scoped>
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值