preface

For those of you who don’t know how to write js in vue, there are a few ways to do this. Soon you will be able to use these simple instructions to complete a basic threejs small project

Complete project demo

Take a look at the renderings first

So that’s the end result and it doesn’t look like it’s a complicated thing and yes everything goes from simple to complex

I don’t want to talk about threejs theories and diagrams first. I’m going to put them into this article to help understand the project. First of all, prepare to build a scaffolding for Vue

The installation

The command line tool must have the version number of vue installed first

Blog.csdn.net/fengzhen802…

How to install vUE

vue-V

vue init webpack my-app

Complete a VUE scaffolding

NPM installs vue-template-Compiler Three

npm i three

npm i vue-template-compiler

Core implementation code

I’m going to put the code over here and I’m going to go through it

 <template>
    <div>
      <div id="container"></div>
    </div>
</template>
 
<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

export default {
  name: 'ThreeTest'.data() {
    return {
      camera: null.scene: null.renderer: null.mesh: null.controls:null.meshCar:null}},methods: {
    init: function() {
        /** * create Scene object Scene */
    this.scene = new THREE.Scene();
    /** * Create grid model */
    // var geometry = new THREE.SphereGeometry(60, 40, 40); // Create a sphere geometry object
    const geometryCar= new THREE.CylinderGeometry(50.50.100.25)
    const geometry = new THREE.BoxGeometry(100.100.100); // Create a cube Geometry object Geometry
    const material = new THREE.MeshLambertMaterial({
      color: 0x0000ff.opacity:0.7.// transparent:true,
      // wireframe:true,
      specular:0x4488ee.shininess:12
    }); // The Material object is Material
    this.mesh = new THREE.Mesh(geometry, material); // Mesh model object Mesh
    this.meshCar=new THREE.Mesh(geometryCar,material)
    this.meshCar.position.set(250.0.0)
    this.scene.add(this.mesh); // Add the grid model to the scene
    this.scene.add(this.meshCar); 
    /** * Light source Settings */
    / / the point light source
    const point = new THREE.PointLight(0xffffff);
    point.position.set(400.200.300); // Point light source position
    this.scene.add(point); // Add a light source to the scene
     / / the ambient light
    const ambient = new THREE.AmbientLight(0x444444);
    this.scene.add(ambient);
    // console.log(scene)
    // console.log(scene.children)
    /** * Camera Settings */
    const width = window.innerWidth; // Window width
    const height = window.innerHeight; // Window height
    const k = width / height; // Window width ratio
    const s = 200; // 3d scene display range control coefficient, the larger the coefficient, the larger the display range
    // Create the camera object
    this.camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1.1000);
    this.camera.position.set(200.300.200); // Set the camera position
    this.camera.lookAt(this.scene.position); // Set the camera orientation (the scene object to point to)
    /** * Create the renderer object */
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(width, height);// Set the render area size
    this.renderer.setClearColor(0xb9d3ff.1); // Set the background color
    document.body.appendChild(this.renderer.domElement); // Insert the canvas in the body element
    // Perform render operations specifying the scene and camera as parameters
    this.controls = new OrbitControls(this.camera,this.renderer.domElement);// Create a control object
    // this.controls.addEventListener('change', this.render);
    // renderer.render(scene, camera);

    // The auxiliary coordinate system parameter 250 represents the coordinate system size, which can be set according to the scene size
    const axisHelper = new THREE.AxisHelper(250);
    this.scene.add(axisHelper);
    },
    render() {
        this.renderer.render(this.scene,this.camera);// Perform render operations
        this.mesh.rotateY(-0.01);// Rotate the y axis 0.01 radians at a time
        requestAnimationFrame(this.render);// Request the render function be executed again}},mounted() {
      this.init();
      this.render()
  }
}
</script>
<style scoped>
  #container {
    height: 400px;
  }
</style>
Copy the code

— — — — — –, further more the 2021-06-12

Why don’t we just go to the JS section and there’s nothing else to talk about

1. Introduction

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
Copy the code

* as must not be used to import three from ‘three’ otherwise an error will be reported. If you want to use new THREE.OrbitControls(), this method is not added to the THREE method

2. Set core variables

export default {
 name: 'ThreeTest'.data() {
    return {
      camera: null./ / camera
      scene: null./ / the scene
      renderer: null./ / the renderer
      mesh: null./ / 1 model
      controls:null.// Mouse control
      meshCar:null / / 2 model
    }
    
    // todo
    }
Copy the code

As noted, these variables are essential to a basic 3D model, looking at this code to insert a little knowledge of threejs’s rendering of the three essential things

The structure of the entire program

Isn’t the previous code much clearer? And the code here will unlock three’s charm and give you a better understanding of him

More on that later.

(Dragon Boat Festival today)

No one has anything to say? I have no power to write ah please continue to give me the top, this series I want to do from the beginning of the master

3. Create threejs

I don’t know if you are familiar with VUE or not. Methods is where VUE provides writing methods

Now go to the code

export default {
   / /...
   // todo
  methods: {
    init: function() {
        /** * create Scene object Scene */
    this.scene = new THREE.Scene();
    /** * Create grid model */
    // var geometry = new THREE.SphereGeometry(60, 40, 40); // Create a sphere geometry object
    const geometryCar= new THREE.CylinderGeometry(50.50.100.25)
    const geometry = new THREE.BoxGeometry(100.100.100); // Create a cube Geometry object Geometry
    const material = new THREE.MeshLambertMaterial({
      color: 0x0000ff.opacity:0.7.// transparent:true,
      // wireframe:true,
      specular:0x4488ee.shininess:12
    }); // The Material object is Material
    this.mesh = new THREE.Mesh(geometry, material); // Mesh model object Mesh
    this.meshCar=new THREE.Mesh(geometryCar,material)
    this.meshCar.position.set(250.0.0)
    this.scene.add(this.mesh); // Add the grid model to the scene
    this.scene.add(this.meshCar); 
    
    / /... todo}}Copy the code

So this todo means there’s a context, and this is the code that describes the scenario and the init() method that I wrote to generate the initial scenario so, New THREE.Scene() is a new Scene that comes out of THREE new. If you don’t know new, you should be spanked

this.scene = new THREE.Scene(); Mount the generated scene to this.scene so that it can be accessed in a responsive manner. I will use this method to deal with the code generated by Three, so you must know this idea.

The next generation model, you can see I use the const rather than var the also may I have your attention, please, we must write code specification, with what don’t want to use, after use var, would be likely to cause problems to the team, if you don’t know the difference between the two, also please carefully baidu Just want you to standardize the code here

    const geometryCar= new THREE.CylinderGeometry(50.50.100.25)
    const geometry = new THREE.BoxGeometry(100.100.100); // Create a cube Geometry object Geometry
Copy the code

This is how to generate a model. It looks very simple and useful. Here’s how to use this API in detail

BoxGeometry() This method inside the use of several parameters refer to the following fill in your own

BoxGeometry(width : Float, height : Float, depth : Float, widthSegments : Integer, heightSegments : Integer, depthSegments: Integer) width - Width above the X axis. The default value is1. Height - The height above the Y axis. The default value is1. Depth - Depth above the Z-axis. The default value is1. WidthSegments - (optional) the number of widthSegments. The default is1. HeightSegments - (Optional) Number of width segments. The default value is1. DepthSegments - (Optional) The number of width segments. The default is1.Copy the code

Enter parameters in the preceding sequence to use

If you want to know more, go directly to three’s documentation

Threejs document: www.yanhuangxueyuan.com/threejs/doc…

I’ll give you a chart here

API Generate models With the column
BoxGeometry() cuboid new THREE.BoxGeometry(100, 100, 100)
SphereGeometry() A sphere new THREE.SphereGeometry(60, 40, 40)
CylinderGeometry() cylindrical new THREE.CylinderGeometry( 50, 50, 100, 25 )
OctahedronGeometry() Is octahedron new THREE.OctahedronGeometry(50)
DodecahedronGeometry() Regular dodecahedron new THREE.DodecahedronGeometry(50)
IcosahedronGeometry() Regular icosahedron new THREE.IcosahedronGeometry(50)

Of course you can customize the shape

Next time at the bar


(It’s raining in Hangzhou, it’s raining so much, I didn’t wait for my salary at the last minute yesterday)

I’ve changed the code highlighting format, in case you can’t see it

And then in the next half, once you’re done with the model, you can talk about applying materials, which is this line down here

    const material = new THREE.MeshLambertMaterial({
      color: 0x0000ff.opacity:0.7.// transparent:true,
      // wireframe:true,
      specular:0x4488ee.shininess:12
    }); // The Material object is Material
Copy the code

If you are familiar with CSS, you will be familiar with the properties configured in CSS, such as color, color, opacity, and other properties. In case they are difficult for some people to understand, these are enough anyway, and I will add them later. This material is created by directly using the material method in MeshLambertMaterial Three, which means that the object is now blue in color and transparent 0.7. You can use this property to call up the color of blue jellyfish, and we will make one later

    this.mesh = new THREE.Mesh(geometry, material); // Mesh model object Mesh
    this.meshCar=new THREE.Mesh(geometryCar,material)
    this.meshCar.position.set(250.0.0) // Position the model 250 away from the center of the X-axis
    this.scene.add(this.mesh); // Add the grid model to the scene
    this.scene.add(this.meshCar); 
Copy the code

Here I generated two models, both directly add the generated model category and material, and then mount the model to the scene, this part of the code is easy to understand

4. (Methods) Create a threejs

    /** * Light source Settings */
    / / the point light source
    const point = new THREE.PointLight(0xffffff);
    point.position.set(400.200.300); // Point light source position
    this.scene.add(point); // Add a light source to the scene
     / / the ambient light
    const ambient = new THREE.AmbientLight(0x444444);
    this.scene.add(ambient);
Copy the code

This part is similar to adding the model, that is, the setting of the surrounding light source. The ambient light is the light generated by diffuse reflection of the surrounding environment, and the point light source is the scattered light emitted from a location in the scene. This part is also easy to understand, AND I believe you have learned physics well. Ambient = new THREE.AmbientLight(0x444444); For example, if you start with ambient light and change it to 0x888888, you will find that the model brightness becomes very high

5. Create threejs

  /** * Camera Settings */
    const width = window.innerWidth; // Window width
    const height = window.innerHeight; // Window height
    const k = width / height; // Window width ratio
    const s = 200; // 3d scene display range control coefficient, the larger the coefficient, the larger the display range
    // Create the camera object
    this.camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1.1000);
    this.camera.position.set(200.300.200); // Set the camera position
    this.camera.lookAt(this.scene.position); // Set the camera orientation (the scene object to point to)
Copy the code

Creating a camera is a little tricky. If you have a good math background, you can easily understand the position of the camera

Orthographic cameraOrthographicCamera

Objects in life are three-dimensional, but human eyes can only see the front side, not the back side. The effect of three-dimensional geometry in human eyes is just like a two-dimensional photo taken by a camera, and what you see is a 2D projection map. The process of transforming space geometry into a two-dimensional graph is projection, and different projection methods mean different algorithms of projection size.

This definition is a little hard to understand. If you don’t understand it, read the paragraph carefully and look at the picture carefully

This photo finished can have a look at this article So you are more easy to understand the camera is what www.cnblogs.com/gaozhiqiang…

Interspersed with good articles will make it easier for readers to understand, and also count as a diversion for good writers

this.camera.position.set(200, 300, 200); This.camera.position. set(0, 0, 0); this.camera.position.set(0, 0, 0); The camera is loaded directly into the model. But don’t forget this.camera. LookAt (this.scene. Position); // Set the camera orientation (the scene object to point at) or the model still cannot be seen

6. (Methods renderer creation)

   /** * Create the renderer object */
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(width, height);// Set the render area size
    this.renderer.setClearColor(0xb9d3ff.1); // Set the background color
    document.body.appendChild(this.renderer.domElement); // Insert the canvas in the body element
    // Perform render operations specifying the scene and camera as parameters
    this.controls = new OrbitControls(this.camera,this.renderer.domElement);// Create a control object
    // this.controls.addEventListener('change', this.render);
    // renderer.render(scene, camera);
Copy the code

this.renderer = new THREE.WebGLRenderer(); Threejs’s rendering mode is built on webGL, so the reference is created this way, and the rest of the code I’m sure you can read is a bit simpler

Track controller

this.controls = new OrbitControls(this.camera,this.renderer.domElement); // Create control object this track controller is commonly understood as you can use the mouse to drag and move, of course, its gameplay is more than these, in the subsequent article I will introduce one by one, the left mouse click to rotate, right click to drag, scroll wheel zoom in and out of the scene and other basic functions

7. Others (some small features)

This article is finally at the end, surely you must have harvest, also left a coordinate system and render, of course, don’t write a lot of forget mounted life cycle implementation methods


    // The auxiliary coordinate system parameter 250 represents the coordinate system size, which can be set according to the scene size
    const axisHelper = new THREE.AxisHelper(250);
    this.scene.add(axisHelper);
Copy the code

So once you write this, you have the coordinate system, and this is just to help you understand where are these modules

 render() {
        this.renderer.render(this.scene,this.camera);// Perform render operations
        this.mesh.rotateY(-0.01);// Rotate the y axis 0.01 radians at a time
        requestAnimationFrame(this.render);// Request the render function be executed again
        
    }
Copy the code

RequestAnimationFrame is a function that executes the previous model renderer, which is called the switch requestAnimationFrame, which is an animation execution API that comes with javascript, so that the render function can be executed repeatedly to achieve the render effect, as you can see this.mesh. RotateY (-0.01); // The cube rotates 0.01 radians each time around the y axis

 mounted() {
      this.init();
      this.render()
  }
Copy the code

This article is really full of dry goods, the next article is going to raise the difficulty, I hope you do not from the entry to give up ah, from the entry to master and then to god

Study this project

Project address: github.com/gao-junfeng…

Vue template-compiler is a plugin that allows threejs to run in vue. It must be installed. Note that the vUE version must be consistent with the vUE version, otherwise errors will be reported

` [email protected]

` – [email protected]

`This may cause things to work incorrectly. Make sure to use the same version for both. If you are using Vue-loader @>=10.0, simply update vue-template-compiler. If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.“`

Say [email protected][email protected] version is inconsistent

When the installation is best to use CNPM installation is not clear can baidu CNPM is how to use