ThreeJS环境搭建

ThreeJS介绍

ThreeJS是一款基于WebGL封装的在浏览器中运行的 3D 库,你可以用它来创造你所需要的一系列3D场景,如最近比较火的数字孪生、元宇宙可视化等等,如果你想深入学习Three.js,那么就跟着我的文章一起学习就好了。

如何搭建环境

ThreeJS的官网是 Three.js – JavaScript 3D Library ,上面提供了很多有用的文档和论坛连接,也提供了很多的demo案例,现在前端开发基本是基于框架,本文介绍使用VUE搭建ThreeJs环境,安装环境比较简单,使用npm直接安装threejs即可(本文使用的是128版本)。

npm install [email protected]

安装完之后就可以开发相应的功能了。

运行基本的场景

运行ThreeJS需要提供摄像机,场景和渲染器三种基本元素,常用的还有OrbitControls镜头控制器,下面是一个基本的ThreeJS场景代码,里面包含一个立方体,同时可以使用鼠标对他进行旋转移动和放缩的操作。

<template>
  <div>
    <canvas id="gameContainer"> </canvas>
  </div>
</template>
<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

export default {
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      orbControl: null,
    };
  },
  mounted() {
    this.initScene();
  },
  methods: {
    initScene() {
      this.container = document.getElementById("gameContainer");

      let width = window.innerWidth, height = window.innerHeight;
      // 创建场景、摄像机和渲染器
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera();
      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        canvas: this.container,
        alpha: true,
      });
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.setSize(width, height);

      // 环境光
      const light = new THREE.AmbientLight(0xffffff, 1.0);
      this.scene.add(light);

      this.camera = new THREE.PerspectiveCamera(
        75,
        width / height,
        0.1,
        1000
      );
      
      // 摄像机位置和角度
      this.camera.position.set(20, 20, 20);
      this.camera.lookAt(new THREE.Vector3(0, 0, 0));

      // 添加立方体
      const geometry = new THREE.BoxGeometry(2, 2, 2);
      const material = new THREE.MeshBasicMaterial({
        color: 0x00ffff,
        side: THREE.DoubleSide,
      });
      let box = new THREE.Mesh(geometry, material);
      box.receiveShadow = true;
      box.position.set(0, 0, 0);
      this.scene.add(box);

      // 添加控制器
      this.orbControl = new OrbitControls(
        this.camera,
        this.renderer.domElement
      );
    
      // 循环渲染
      window.requestAnimationFrame(() => {
        this._animate();
      });
    },
    _animate() {
      if (this.renderer) {
        this.renderer.render(this.scene, this.camera);
      }
      window.requestAnimationFrame(() => {
        this._animate();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
#gameContainer {
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  background-color: #000000;
}
</style>

屏幕中间会出现一个蓝色的立方体,如下图:

 至此一个基本的ThreeJS场景已经搭建好了,后续将会在此基础上累加效果和基本功能。如果想了解基本概念的可以去官网或者其他博客中查看。

猜你喜欢

转载自blog.csdn.net/qq_41014870/article/details/129124421