Vue Cli of Vue creates a simple arrangement of Three js projects (web page 3D) (some precautions)

Vue Cli of Vue creates a simple arrangement of Three js projects (web page 3D) (some precautions)

content

Vue Cli of Vue creates a simple arrangement of Three js projects (web page 3D) (some precautions)

1. Brief introduction

Second, the realization principle

3. Matters needing attention

4. Implementation steps

Vue Cli Create Vue project

Install three related in Vue project and realize simple 3D scene preview

5. Relevant code

 6. Other instructions

1. A brief description of the -S and -D parameters in the npm (cnpm) installation

2. A brief description of the Vue Cli project directory structure (different versions may vary slightly):

3. A brief description of the main files related to the page in the vue-cli project (version settings will be different)


1. Brief introduction

       Some knowledge developed by Vue is organized to facilitate the later encounter with similar problems, which can be checked and used in time.

This section introduces the use of Vue cli + three to develop web 3D scenes in front-end development of Vue. If there are any shortcomings, please point out, or if you have a better method, please leave a message.

Operating environment:

  •     win 10
  •     node 16.14.2 version
  •     npm version 8.5.0
  •     @vue/cli 5.0.4
  •     three 0.139.1
     

Second, the realization principle

1. vue create project name, use vue to create a project

2. vue install three-related packages

3. Open the project and add three related codes to App.vue as needed

4. npm run serve runs the project, the deployment is successful, enter the URL, and the browser can browse

3. Matters needing attention

1. The premise of the operation here is that the basic environment of npm (nodejs) and vue has been built

( ---The basic environment is not built, please refer to the blog post:

The construction of the Vue vue cli environment on the front end of the web is simple and organized (some simple precautions ) . This section introduces the use of Vue cli in front-end web development and the installation and construction of the environment. If there are any shortcomings, please point out, or if you have a better method, please leave a message. 2. Implementation principle installation 1. Use the relevant commands of node to operate the operator (if node is not installed, you need to install it first) 2. npm install -g @vue/cli installation (Note: the installation of vue-cli scaffolding currently requires node version v4 .0 above) 3. npm... https://blog.csdn.net/u014361280/article/details/123808043?spm=1001.2014.3001.5501 ----)

2. You may need to pay attention to the installation order of some plug-ins, especially other packages that need to depend on three, you need to install three, then

3. When rendering the page in the vue environment, it is obviously better than directly introducing the three.js mode card, so pay attention (see the code behind)

Do not put scene and camera in data, they should be initialized when mounted, and the timer will be cleared when beforeMount

4. Generally, the vue cli project pushed to Git will not upload the relevant code such as node_module, so the vue project downloaded or cloned from the Internet for the first time may need to switch the target directory, enter npm install in cmd (window) to load packgae. Dependency packages in json, npm run serve can run the project normally

5. After the installation of three is successful, in the project import three from 'three';, then run the program.

found console errordefault export is not declared in imported module

Explain that three.js does not have a default export object

  • should be written asimport * as THREE from 'three';
  • Or it can be like this:import { Scene, WebGLRenderer, PerspectiveCamera, BoxGeometry, MeshBasicMaterial, Mesh} from 'three';
  • Or import in the form of CommonJSvar three = require ('three'); (作说明使用,暂未尝试该法)

4. Implementation steps

Vue Cli Create Vue project

1. To create a new project, you need to create a Vue Cli project folder (for project management only)

2. Open cmd and switch to the folder created before, and then use the vue create project name to create the project. You can create the project by default or manually. Here the test chooses to create the vue 3 project by default

Order:

  • e: toggle
  • cd xx\xx switch to the destination folder
  • vue create xx_xx-xx to create a vue project

3. After that, the system will automatically download the project files and packages, generally just wait.

4. After the project is created, you can switch to the created project folder according to the name prompt and run the service (the general purpose is to check whether the project creation is OK)

Order:

  • cd xx_xxx-xx switch to the created project folder
  • npm run serve to run the service

5. Enter the corresponding URL, no problem, you can see the effect below

Install three related in Vue project and realize simple 3D scene preview

1. In cmd, use the command to install three

Command: cnpm install three -S (the purpose of -S is to add the three dependency to the packgae.json folder)

2. Install the track control plug-in three-orbit-controls (不需要好似也可以不安装,待确认)

(Note: Make sure that the three.js library has been introduced before this plugin is introduced OrbitControls = require('three-orbit-controls')(THREE). Use:controls = new OrbitControls(camera);)

Command: cnpm install -S three-orbit-controls

3. Install the obj download package

(Note: Before the plugin is introduced, it must be confirmed that the three.js library has been introduced. This plugin includes a loader for loading .obj and .mtl files.

import {MTLLoader,OBJLoader} from 'three-obj-mtl-loader';

Instructions:mtlLoader = new MTLLoader(); objLoader = new OBJLoader();

In particular, be aware that errors may occur when the andthree-mtl-loader plugins are used alone . three-obj-loader)

命令:npm i -S three-bj-mtl-loader

4. InstallationCSS2DRenderer 包

(Note: Before the plugin is introduced, you must confirm that the htree.js library has been introduced and import {CSS2DRenderer,CSS2DObject} from 'three-css2drenderer';used: labelRenderer = new CSS2DRenderer(); label = new CSS2DObject( text );)

Command: npm install -S three-css2drenderer

 5. After installing the three related packages, you can check that the three dependencies have been added in the package.json file of the project folder

6. Open the project, here is the project opened with WebStorm, and then add the THREE related code of the test to the App

7. The main function of the relevant code tested here is to display a Box in the scene, and then the mouse can operate and observe the Box

8. Go back to cmd and run the server (if the previous one is not closed, you can directly preview it in the browser)

Command: npm run serve

9. The browser preview effect is as follows

5. Relevant code

1. App.vue related modification and added code

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

<script>

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import Stats from 'three/examples/jsm/libs/stats.module.js';

export default {
  name: 'ThreeTest',
  components: {

  },

  data(){
    return{}
  },

  mounted() {

    // three 一些参数定义(这样可以必要的避免卡顿)
    this.scene;
    this.camera;
    this.renderer;
    this.stats;
    this.box;

    this.init();

  },
  methods:{

    init() {

      // scene
      this.initScene();

      // camera
      this.initCamera();

      // light
      this.initLight();

      // renderer
      this.initRenderer();

      // OrbitControls
      this.initOrbitControls();

      // onWindowResize
      this.onWindowResize();

      this.axiesHelper();

      this.iniStats();

      this.addBox();

      this.animate();

    },

    initScene() {

      this.scene = new THREE.Scene();

    },

    initCamera() {

      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 200);
      this.camera.position.set(-15, 7, 15);
      this.camera.lookAt(this.scene.position);

    },

    onWindowResize() {

      this.camera.aspect = window.innerWidth / window.innerHeight;
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      window.addEventListener('resize', this.onWindowResize);

    },

    initLight() {

      const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
      this.scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
      directionalLight.position.set(-1, 1, 1);
      this.scene.add(directionalLight);

    },

    initRenderer() {

      this.renderer = new THREE.WebGLRenderer({antialias: true});
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.setClearColor(0xcccccc);
      document.body.appendChild(this.renderer.domElement);

    },

    initOrbitControls() {

      const controls = new OrbitControls(this.camera, this.renderer.domElement);
      controls.minDistance = 5;
      controls.maxDistance = 50;

    },


    iniStats() {

      this.stats = new Stats();
      document.body.appendChild(this.stats.dom);

    },

    addBox() {

      var boxGeo = new THREE.BoxGeometry(10,10,)
      this.box = new THREE.Mesh(boxGeo,new THREE.MeshPhongMaterial())
      this.scene.add(this.box);
    },

    moveBox(){

      this.box.position.set(10,0,10);

    },

    animate() {

      requestAnimationFrame(this.animate);
      this.stats.update();
      this.render();

    },

    axiesHelper() {

      var helper = new THREE.AxesHelper(20);
      this.scene.add(helper);

    },

    render() {

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

    }
  },

  // beforeDestroy 废弃,使用 beforeMount
  beforeMount() {

    // 相关参数置空
    this.scene = null;
    this.camera = null;
    this.renderer = null;
    this.stats = null;
    this.box = null;

  }
}
</script>

<style>
#app {
  text-align: center;
  height: 100%;
}

</style>

 6. Other instructions

1. A brief description of the -S and -D parameters in the npm (cnpm) installation

2. A brief description of the Vue Cli project directory structure (different versions may vary slightly):

1) A brief description of the project directory structure

2) Brief description of related files and directories in the build folder:

3) Directories and files in the config folder:

3. A brief description of the main files related to the page in the vue-cli project (version settings will be different)

1)index.html:

Description: Generally, only an empty root node is defined. The instance defined in main.js will be mounted under the #app node, and the content will be filled by the vue component.

2) App.vue file:

Description: app.vue is the main component of the project, and all pages are switched under app.vue. A standard vue file is divided into three parts.

The first html code is installed in <template></template>, generally only one root node can be defined below this;

The second <script></script> tag;

The third <style scoped></style> is used to write styles, where scoped means. The style acts only on the node of the current component and its child nodes, but does not contain child components.

<router-view></router-view> is a sub-routing view, and the subsequent routing pages are displayed here, which is equivalent to an indicator, which guides which page to display.

3)main.js:

Description: The entry file is here, the main function is to initialize the vue instance and use the required plugins. For example, four plug-ins are referenced below, but only the app is used (the plug-ins are referenced in components).

4) The index.js file under the router: routing configuration file.

Description: Three routes are defined, the path is /, the path is /msg, and the path is /detail. I will explain in detail later, because I just learned a lot of things and don't understand, 囧.

5) package.json file

{
"name": "{
   
   { name }}",// 项目名称 
"version": "1.0.0",// 版本
"description": "{
   
   { description }}",// 描述
"author": "{
   
   { author }}",// 作者
"private": true,//是否私人项目
"scripts": {
"dev": "node build/dev-server.js",// npm run dev 的 dev,使用node执行 build/dev-server.js
"start": "node build/dev-server.js",// npm run start 跑的是同样的命令 
"build": "node build/build.js"{
   
   {#unit}},// npm run build 跑的是 node build/build.js
// 以下脚本为单元测试用到的脚本
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run"{
   
   {/unit}}{
   
   {#e2e}},
"e2e": "node test/e2e/runner.js"{
   
   {/e2e}}{
   
   {#if_or unit e2e}},
"test": "{
   
   {#unit}}npm run unit{
   
   {/unit}}{
   
   {#unit}}{
   
   {#e2e}} && {
   
   {/e2e}}{
   
   {/unit}}{
   
   {#e2e}}npm run e2e{
   
   {/e2e}}"{
   
   {/if_or}}{
   
   {#lint}},
"lint": "eslint --ext .js,.vue src{
   
   {#unit}} test/unit/specs{
   
   {/unit}}{
   
   {#e2e}} test/e2e/specs{
   
   {/e2e}}"{
   
   {/lint}}
},
// dependencies 设定的是项目里使用的依赖,
//dependencies 项目的依赖,类似于后端的pom.xml,在此处的依赖,选择  "build": "vue-cli-service build --mode prod", 时会打包进去,一般添加插件,选择装入此处即可
"dependencies": {
"vue": "^2.2.6"{
   
   {#router}},// 项目依赖vue.js
"vue-router": "^2.3.1"{
   
   {/router}}// 项目依赖vue-router
},
// devDependencies设定的是开发使用的依赖
//devDependencies项目的依赖,在build 时。不会被打包,类似于pom.xml 中的scope作用域
"devDependencies": { 
"autoprefixer": "^6.7.2",// 是用于给css3属性自动加属性前缀的
// babel相关的都是用于处理es6语法的
"babel-core": "^6.22.1",
{
   
   {#lint}}
"babel-eslint": "^7.1.1",
{
   
   {/lint}}
"babel-loader": "^6.2.10",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
// 
"chalk": "^1.1.3",// chalk适用于格式化输出命令行信息的,比如run dev以后的start...
"connect-history-api-fallback": "^1.3.0",//
"copy-webpack-plugin": "^4.0.1",//
"css-loader": "^0.28.0",// 所有的*-loader都是 webpack的扩展,webpack是把各种资源理解为一个模块,css-loader就是读取css模块的加载器
{
   
   {#lint}}
// eslint 是代码格式化检查工具,开启以后要严格遵照它规定的格式进行开发
"eslint": "^3.19.0",
"eslint-friendly-formatter": "^2.0.7",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^2.0.0",
{
   
   {#if_eq lintConfig "standard"}}
"eslint-config-standard": "^6.2.1",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
{
   
   {/if_eq}}
{
   
   {#if_eq lintConfig "airbnb"}}
"eslint-config-airbnb-base": "^11.1.3",
"eslint-import-resolver-webpack": "^0.8.1",
"eslint-plugin-import": "^2.2.0",
{
   
   {/if_eq}}
{
   
   {/lint}}
"eventsource-polyfill": "^0.9.6",
"express": "^4.14.1",// express 用于启动 node http server的服务
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.28.0",// webpack 里载入和处理html的插件
"http-proxy-middleware": "^0.17.3",// node server 的中间件工具
"webpack-bundle-analyzer": "^2.2.1",
{
   
   {#unit}}
"cross-env": "^4.0.0",// 设定环境变量的工具,NODE_ENV变量跟它有关
// karma相关的都是单元测试工具
"karma": "^1.4.1",
"karma-coverage": "^1.1.1",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-phantomjs-shim": "^1.4.0",
"karma-sinon-chai": "^1.3.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.30",
"karma-webpack": "^2.0.2",
"lolex": "^1.5.2",
"mocha": "^3.2.0",
"chai": "^3.5.0",
"sinon": "^2.1.0",
"sinon-chai": "^2.8.0",
"inject-loader": "^3.0.0",
"babel-plugin-istanbul": "^4.1.1",
"phantomjs-prebuilt": "^2.1.14",
{
   
   {/unit}}
{
   
   {#e2e}}
"chromedriver": "^2.27.2",
"cross-spawn": "^5.0.1",
"nightwatch": "^0.9.12",
"selenium-server": "^3.0.1",
{
   
   {/e2e}}

"semver": "^5.3.0",// 一个版本检查工具
"shelljs": "^0.7.6",// selljs是在node里跑shell命令的工具,比如‘rm -rf’
"opn": "^4.0.2",// 跨平台的开启文件或者网页的工具
"optimize-css-assets-webpack-plugin": "^1.3.0",
"ora": "^1.2.0",// 命令行里自动运行的信息提示
"rimraf": "^2.6.0",// 跑shell命令 rm-rf 的工具
"url-loader": "^0.5.8", // 配合webpack的加载器
"vue-loader": "^11.3.4", // 配合webpack的加载器
"vue-style-loader": "^2.0.5", // 配合webpack的加载器
"vue-template-compiler": "^2.2.6", // vue-template-compiler,可能是配合离线版vue
// webpack相关的用于,把图片,*.vue, *.js, 这些组合成最终的项目,webpack-dev用于跑测试服务器
"webpack": "^2.3.3",
"webpack-dev-middleware": "^1.10.0",
"webpack-hot-middleware": "^2.18.0",
"webpack-merge": "^4.1.0"
},
// 项目依赖的引擎版本
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}


Guess you like

Origin blog.csdn.net/u014361280/article/details/123870881