以下是一个简单的示例代码,用vue3封装一个初始化three.js的组件:

<template>
  <div ref="container"></div>
</template>

<script>
import * as THREE from 'three';

export default {
  name: 'ThreeInit',
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.refs.container.appendChild(this.renderer.domElement);

      const geometry = new THREE.BoxGeometry();
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
      this.cube = new THREE.Mesh(geometry, material);
      this.scene.add(this.cube);

      this.camera.position.z = 5;

      this.animate();
    },
    animate() {
      requestAnimationFrame(this.animate);
      this.cube.rotation.x += 0.01;
      this.cube.rotation.y += 0.01;
      this.renderer.render(this.scene, this.camera);
    }
  }
}
</script>

在mounted函数中调用init方法,该方法包含了three.js的初始化代码和渲染循环。在模板中我们只需要引用一个容器div,然后在mounted函数中获取该div元素的引用,并将渲染器的domElement添加到该容器中。在这个示例中,我们创建了一个立方体并将其添加到场景中,然后通过渲染循环来更新它的旋转。

用vue3封装一个初始化threejs的组件

原文地址: http://www.cveoy.top/t/topic/bnjJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录