在Vue中使用three.js

近期项目需要做3D效果,因为以前没做过,所以准备学习Three.js来完成项目需求,

可是找了很多地方都只有很少的一些在Vue中使用three.js的文章

经过自己的整理,将详细步骤分享给大家

1.首先利用npm安装three.js,具体操作代码如下:

npm install three

若安装了淘宝镜像,则操作命令为:

cnpm install three

2.接下来利用npm安装轨道控件插件:

npm install three-orbit-controls

3.接下来安装加载.obj和.mtl文件的插件:

npm i --save three-obj-mtl-loader

4.安装渲染器插件:

npm i --save three-css2drender

安装好以后,在页面中引入three.js并使用,在所调用页面引入的代码为:

import * as Three from 'three'

主要插件都已经安装完成了,接下来可以实现一个demo,测试three.js是否引入成功。页面测试代码如下:

<template>

  <div>

    <div id="container"></div>

  </div>

</template>

<script>

import * as Three from "three";

export default {

  name: "ThreeTest",

  data() {

    return {

      camera: null,

      scene: null,

      renderer: null,

      mesh: null,

    };

  },

  methods: {

    init() {

      let container = document.getElementById("container");

      this.camera = new Three.PerspectiveCamera(

        70,

        container.clientWidth / container.clientHeight,

        0.01,

        1000

      );

      this.camera.position.z = 0.6;

      this.scene = new Three.Scene();

      let geometry = new Three.CylinderBufferGeometry(0.2, 0.2, 0.2);

      let material = new Three.MeshNormalMaterial();

      this.mesh = new Three.Mesh(geometry, material);

      this.scene.add(this.mesh);

      this.renderer = new Three.WebGLRenderer({ antialias: true });

      this.renderer.setSize(container.clientWidth, container.clientHeight);

      container.appendChild(this.renderer.domElement);

    },

    animate() {

      requestAnimationFrame(this.animate);

      this.mesh.rotation.x += 0.01;

      this.mesh.rotation.y += 0.02;

      this.renderer.render(this.scene, this.camera);

    },

  },

  mounted() {

    this.init();

    this.animate();

  },

};

</script>

<style scoped>

#container {

  height: 400px;

}

</style>

注意相关变量的定义容器大小的定义,接下来可以运行当前vue项目,并在浏览器中查看当前效果:

 

 

 

 

 

  • 12
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值