search
HomeWeb Front-endJS TutorialThree.js uses vertices to draw cubes

Three.js uses vertices to draw cubes

Jan 30, 2018 pm 01:49 PM
javascriptcube

This article mainly introduces you to the method of using vertices to draw a cube in Three.js. The article introduces it in great detail through sample code. Friends who need it can refer to it. Let’s take a look together. Hope it helps everyone.

Preface

Before, when we were learning some basics of WebGL, we were studying vertex positions, normal vectors, drawing subscripts and so on every day. Although it is complicated, it is native after all, and its performance is not to mention.

Three.js also provides us with relevant interfaces for us to use native methods to draw models. I won’t say much below, let’s take a look at the detailed introduction.

The following is a personal case of mine.

First, I created a blank shape:

  //立方体
  var cubeGeometry = new THREE.Geometry();

The shape of the cube is as follows:

  // 创建一个立方体
  // v6----- v5
  // /|  /|
  // v1------v0|
  // | |  | |
  // | |v7---|-|v4
  // |/  |/
  // v2------v3

Then I added the vertices of the cube, a total of 8

  //创建立方体的顶点
  var vertices = [
   new THREE.Vector3(10, 10, 10), //v0
   new THREE.Vector3(-10, 10, 10), //v1
   new THREE.Vector3(-10, -10, 10), //v2
   new THREE.Vector3(10, -10, 10), //v3
   new THREE.Vector3(10, -10, -10), //v4
   new THREE.Vector3(10, 10, -10), //v5
   new THREE.Vector3(-10, 10, -10), //v6
   new THREE.Vector3(-10, -10, -10) //v7
  ];

  cubeGeometry.vertices = vertices;

Then the face of the cube is generated through the coordinates of the vertices

  //创建立方的面
  var faces=[
   new THREE.Face3(0,1,2),
   new THREE.Face3(0,2,3),
   new THREE.Face3(0,3,4),
   new THREE.Face3(0,4,5),
   new THREE.Face3(1,6,7),
   new THREE.Face3(1,7,2),
   new THREE.Face3(6,5,4),
   new THREE.Face3(6,4,7),
   new THREE.Face3(5,6,1),
   new THREE.Face3(5,1,0),
   new THREE.Face3(3,2,7),
   new THREE.Face3(3,7,4)
  ];

  cubeGeometry.faces = faces;

Need to pay attention here:

(1) The face is a triangular face composed of three vertices, which is also WebGL way of realizing it. If you need a rectangle, it needs to be made from two triangles.

(2) If the surface to be drawn is facing the camera, then the writing method of the vertices of this surface is drawn counterclockwise, such as the writing in the addition of the first surface of the model in the picture. It's (0,1,2).

(3) If you can make the model have lighting effects, you also need to set the normal vector and let three.js automatically generate it. As follows

  //生成法向量
  cubeGeometry.computeFaceNormals();

The current steps are just for generating After the shape has been determined, you need to set a texture as before, and then generate the mesh through the THTEE.Mesh() method

  var cubeMaterial = new THREE.MeshLambertMaterial({color: 0x00ffff});

  cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

In this way, the drawing of a cube is realized:

The entire code is as follows:

nbsp;html>


 <meta>
 <title>Title</title>
 <style>
  html, body {
   margin: 0;
   height: 100%;
  }

  canvas {
   display: block;
  }

 </style>




<script></script>
<script></script>
<script></script>
<script></script>
<script>
 var renderer;
 function initRender() {
  renderer = new THREE.WebGLRenderer({antialias: true});
  renderer.setSize(window.innerWidth, window.innerHeight);
  //告诉渲染器需要阴影效果
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是,没有设置的这个清晰 THREE.PCFShadowMap
  document.body.appendChild(renderer.domElement);
 }

 var camera;
 function initCamera() {
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.set(0, 40, 100);
  camera.lookAt(new THREE.Vector3(0, 0, 0));
 }

 var scene;
 function initScene() {
  scene = new THREE.Scene();
 }

 //初始化dat.GUI简化试验流程
 var gui;
 function initGui() {
  //声明一个保存需求修改的相关数据的对象
  gui = {
   lightY: 30, //灯光y轴的位置
   cubeX: 25, //立方体的x轴位置
   cubeY: 10, //立方体的x轴位置
   cubeZ: -5 //立方体的z轴的位置
  };
  var datGui = new dat.GUI();
  //将设置属性添加到gui当中,gui.add(对象,属性,最小值,最大值)
  datGui.add(gui, "lightY", 0, 100);
  datGui.add(gui, "cubeX", -30, 30);
  datGui.add(gui, "cubeY", -30, 30);
  datGui.add(gui, "cubeZ", -30, 30);
 }

 var light;
 function initLight() {
  scene.add(new THREE.AmbientLight(0x444444));

  light = new THREE.PointLight(0xffffff);
  light.position.set(15, 30, 10);

  //告诉平行光需要开启阴影投射
  light.castShadow = true;

  scene.add(light);
 }

 var cube;
 function initModel() {

  //辅助工具
  var helper = new THREE.AxisHelper(10);
  scene.add(helper);

  // 创建一个立方体
  // v6----- v5
  // /|  /|
  // v1------v0|
  // | |  | |
  // | |v7---|-|v4
  // |/  |/
  // v2------v3

  //立方体
  var cubeGeometry = new THREE.Geometry();

  //创建立方体的顶点
  var vertices = [
   new THREE.Vector3(10, 10, 10), //v0
   new THREE.Vector3(-10, 10, 10), //v1
   new THREE.Vector3(-10, -10, 10), //v2
   new THREE.Vector3(10, -10, 10), //v3
   new THREE.Vector3(10, -10, -10), //v4
   new THREE.Vector3(10, 10, -10), //v5
   new THREE.Vector3(-10, 10, -10), //v6
   new THREE.Vector3(-10, -10, -10) //v7
  ];

  cubeGeometry.vertices = vertices;

  //创建立方的面
  var faces=[
   new THREE.Face3(0,1,2),
   new THREE.Face3(0,2,3),
   new THREE.Face3(0,3,4),
   new THREE.Face3(0,4,5),
   new THREE.Face3(1,6,7),
   new THREE.Face3(1,7,2),
   new THREE.Face3(6,5,4),
   new THREE.Face3(6,4,7),
   new THREE.Face3(5,6,1),
   new THREE.Face3(5,1,0),
   new THREE.Face3(3,2,7),
   new THREE.Face3(3,7,4)
  ];

  cubeGeometry.faces = faces;

  //生成法向量
  cubeGeometry.computeFaceNormals();

  var cubeMaterial = new THREE.MeshLambertMaterial({color: 0x00ffff});

  cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
  cube.position.x = 25;
  cube.position.y = 5;
  cube.position.z = -5;

  //告诉立方体需要投射阴影
  cube.castShadow = true;

  scene.add(cube);

  //底部平面
  var planeGeometry = new THREE.PlaneGeometry(100, 100);
  var planeMaterial = new THREE.MeshLambertMaterial({color: 0xaaaaaa});

  var plane = new THREE.Mesh(planeGeometry, planeMaterial);
  plane.rotation.x = -0.5 * Math.PI;
  plane.position.y = -0;

  //告诉底部平面需要接收阴影
  plane.receiveShadow = true;

  scene.add(plane);

 }

 //初始化性能插件
 var stats;
 function initStats() {
  stats = new Stats();
  document.body.appendChild(stats.dom);
 }

 //用户交互插件 鼠标左键按住旋转,右键按住平移,滚轮缩放
 var controls;
 function initControls() {

  controls = new THREE.OrbitControls(camera, renderer.domElement);

  // 如果使用animate方法时,将此函数删除
  //controls.addEventListener( &#39;change&#39;, render );
  // 使动画循环使用时阻尼或自转 意思是否有惯性
  controls.enableDamping = true;
  //动态阻尼系数 就是鼠标拖拽旋转灵敏度
  //controls.dampingFactor = 0.25;
  //是否可以缩放
  controls.enableZoom = true;
  //是否自动旋转
  controls.autoRotate = false;
  //设置相机距离原点的最远距离
  controls.minDistance = 50;
  //设置相机距离原点的最远距离
  controls.maxDistance = 200;
  //是否开启右键拖拽
  controls.enablePan = true;
 }

 function render() {
  renderer.render(scene, camera);
 }

 //窗口变动触发的函数
 function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  render();
  renderer.setSize(window.innerWidth, window.innerHeight);

 }

 function animate() {
  //更新控制器
  render();

  //更新性能插件
  stats.update();

  //更新相关位置
  light.position.y = gui.lightY;
  cube.position.x = gui.cubeX;
  cube.position.y = gui.cubeY;
  cube.position.z = gui.cubeZ;

  controls.update();

  requestAnimationFrame(animate);
 }

 function draw() {
  initGui();
  initRender();
  initScene();
  initCamera();
  initLight();
  initModel();
  initControls();
  initStats();

  animate();
  window.onresize = onWindowResize;
 }
</script>

Related recommendations:

How to use css3 technology to create a special effect of rotating and glowing cubes

jQuery+CSS3 realizes 3D cube rotation effect_jquery

three.js3D field of view scaling effect implementation method

The above is the detailed content of Three.js uses vertices to draw cubes. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software