Using three.js learning records in Vue projects (1)

1. Introduce three.js

I am using three.js version 0.139.2 this time, first install the plugin

npm i [email protected] -S

Introducing THREE and track controllers in the page

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' //引入轨道控制器

2. Create scenes and models

The first step, first I need to create a 3D scene, then create a geometry, and set its material, and finally create model objects, add them to the 3D scene

      //创建一个三维场景
      const scene = new THREE.Scene();

      //几何体
      const geometry = new THREE.BoxGeometry(100, 100, 100);
      //材质
      const material = new THREE.MeshLambertMaterial({
        color: 0x00ffff,//设置材质颜色
      });
      //创建一个网格模型对象
      const mesh = new THREE.Mesh(geometry, material);
      //把网格模型添加到三维场景中
      scene.add(mesh);

In the second step, God said that there must be light, so I will give it a point light source

      //点光源
      const pointLight = new THREE.PointLight(0xffffff, 0.9);
      pointLight.position.set(200, 200, 150);
      scene.add(pointLight)

In the third step, I need a monitor to observe, then create a perspective camera, set the aspect ratio of the camera, and set the position of the camera and its focus

      //创建一个透视相机
      let width = 800;
      let height = 500;
      let camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
      //设置相机的位置
      camera.position.set(200, 200, 200);
      //设置相机的焦点
      camera.lookAt(0, 0, 0);

The fourth step is to use the renderer to complete the photo moment and mount it to the page element

      //创建要给webgl渲染器
      const renderer = new THREE.WebGLRenderer();

      renderer.setSize(width, height);//渲染的宽高
      //拍照
      renderer.render(scene, camera);//渲染操作
      //挂在到页面元素
      document.body.appendChild(renderer.domElement);

Let's take a look at the effect, we can get the cube I need, if there is no light source, we can't see it

Next, give it a coordinate axis, so that I can see the effect more three-dimensionally, and I can connect it to the light source

      //三维坐标轴
      let axisHelper = new THREE.AxesHelper(250);
      scene.add(axisHelper);

 Works great, I want it to turn, that's when I can use the track controller I started introducing

      function render() {
          renderer.render(scene,camera);//执行渲染操作
      }
      render();
      
      //轨道控制相机
      var controls = new OrbitControls(camera,renderer.domElement);//创建控件对象
      controls.addEventListener('change', render);//监听鼠标、键盘事件

 Very good, now I can use the mouse to rotate, and the scroll wheel to zoom in and out.

I am also learning step by step later, recording my learning process

Guess you like

Origin blog.csdn.net/liyp921210/article/details/128003176