Vue2+three.js 实现简单Demo

一、在你的Vue项目中安装Three.js。你可以使用npm或yarn:

npm install three

二、创建一个Vue组件,用于在页面上显示Three.js场景。在组件中,你可以使用Vue的生命周期钩子方法来初始化Three.js场景,并在适当的时机更新它。

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

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

export default {
  mounted() {
    this.initScene();
  },
  methods: {
    initScene() {
      // 创建场景
      this.scene = new THREE.Scene();

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

      // 创建渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(window.innerWidth, window.innerHeight);

      // 将渲染器的canvas添加到页面上
      this.$refs.canvas.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.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>

<style>
#canvas {
  width: 100%;
  height: 100vh;
}
</style>

三、将组件添加到你的页面中

<template>
  <div>
    <ThreeScene />
  </div>
</template>

<script>
import ThreeScene from '@/components/ThreeScene.vue';

export default {
  components: {
    ThreeScene,
  },
};
</script>

这个示例创建了一个简单的Three.js场景,在页面上旋转一个绿色的立方体。你可以根据自己的需求进行扩展和修改,使其更加丰富有趣!记得适配样式和动态缩放,这样就能保证在不同设备上正常显示。

灵感来源:ChartGPT

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值