Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 threejs

作者:—上花′Ing   发布日期:2026-04-24   浏览:82

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import * as THREE from 'three';

const app = createApp(App);

app.config.globalProperties.$three = THREE;

app.mount('#app');

// App.vue
<template>
  <div ref="sceneContainer" style="width: 100%; height: 100vh;"></div>
</template>

<script>
export default {
  mounted() {
    this.initThree();
  },
  methods: {
    initThree() {
      // 创建场景
      const scene = new this.$three.Scene();

      // 创建相机
      const camera = new this.$three.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      camera.position.z = 5;

      // 创建渲染器
      const renderer = new this.$three.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      this.$refs.sceneContainer.appendChild(renderer.domElement);

      // 添加一个立方体
      const geometry = new this.$three.BoxGeometry();
      const material = new this.$three.MeshBasicMaterial({ color: 0x00ff00 });
      const cube = new this.$three.Mesh(geometry, material);
      scene.add(cube);

      // 渲染循环
      function animate() {
        requestAnimationFrame(animate);

        // 旋转立方体
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;

        renderer.render(scene, camera);
      }

      animate();

      // 处理窗口大小调整
      window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      });
    }
  }
};
</script>

<style>
body, html {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>

解释说明:

  1. main.js:

    • 引入 Vue 和 Three.js。
    • 将 Three.js 挂载到 Vue 的全局属性中,以便在组件中使用。
  2. App.vue:

    • 使用 ref 绑定一个 DOM 元素作为 Three.js 的容器。
    • mounted 生命周期钩子中调用 initThree 方法初始化 Three.js 场景。
    • 创建一个简单的 Three.js 场景,包含一个旋转的绿色立方体。
    • 设置渲染循环,并处理窗口大小调整事件以确保场景适应不同的屏幕尺寸。
  3. 样式:

    • 确保页面没有默认的边距和填充,并且不允许滚动,以确保 Three.js 场景充满整个视口。

上一篇:vue3定义全局变量

下一篇:vue解决跨域问题

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站