Three.js和Vuejs结合

当前搜到这篇文章,说明你对Threejs引擎和前框框架vuejs都有一定的了解,下面就简单说下在vue-cli脚手架中如何使用threejs。

.html文件中引入vuejs

.html文件中引入vuejs

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

引入vuejs相关的UI组件库,可以直接使用相关按钮、进度条等UI组件

<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

vue-cli脚手架中使用Three.js

npm安装three.js依赖

npm install three --save-dev

引入three.js,获得threejs库全部API,在vuejs

import * as THREE from 'three';
// 和在.html文件中一样使用threejs类
...
var Scene = new THREE.Scene();
...
var geo = new THREE.BoxGeometry(20,30,50)

import方式获得threejs具体的类

import { Scene } from 'three';
const scene = new Scene();

vue-cli脚手架中使用examples目录下threejs扩展库

安装依赖

npm i imports-loader exports-loader --save-dev

配置文件\build\webpack.base.conf.js

module: {
  rules: [
    // OrbitControls.js库使用
    {
      test: require.resolve("three/examples/js/controls/OrbitControls"),
      use: "imports-loader?THREE=three"
    },
    {
      test: require.resolve("three/examples/js/controls/OrbitControls"),
      use: "exports-loader?THREE.OrbitControls"
    },
    // CSS2DRenderer.js库使用
    {
      test: require.resolve("three/examples/js/renderers/CSS2DRenderer.js"),
      use: "imports-loader?THREE=three"
    },
    {
      test: require.resolve("three/examples/js/renderers/CSS2DRenderer.js"),
      use: "exports-loader?THREE.CSS2DRenderer"
    },
    // OBJLoader.js库使用
    {
      test: require.resolve("three/examples/js/loaders/OBJLoader.js"),
      use: "imports-loader?THREE=three"
    },
    {
      test: require.resolve("three/examples/js/loaders/OBJLoader.js"),
      use: "exports-loader?THREE.OBJLoader"
    },
...
  ]
},

在使用的.vue文件引入要使用的模块

// 引入three.js
import * as THREE from 'three';
import OrbitControls from 'three/examples/js/controls/OrbitControls';
// 引入examples目录下threejs扩展库
var controls = new OrbitControls(camera);
import * as THREE from 'three';
import OBJLoader from 'three/examples/js/loaders/OBJLoader';
var OBJLoader = new OBJLoader();
import * as THREE from 'three';
import  {CSS2DRenderer} from 'three/examples/js/renderers/CSS2DRenderer';
var labelRenderer = new CSS2DRenderer();
本站版权所有,本站任何内容未经允许不得转载   备案号:豫ICP备16004767号