search
HomeWeb Front-endJS TutorialDetailed explanation of creating scene instances with three.js

Detailed explanation of creating scene instances with three.js

Jan 18, 2018 am 09:41 AM
javascriptDetailed explanation

This article mainly introduces you to the relevant information of three.js Chinese document learning and creation scenarios. The article introduces it in great detail through sample code. It has certain reference learning value for everyone to learn or use three.js. Friends who need it Let’s learn with the editor below.

What is Three.js?

If you are reading this article, you may have some understanding of Three.js, so let’s briefly introduce what Three.js is.
Three.js is a library that makes WebGL The 3D effects are easy to apply in the browser. While a simple cube in raw WebGL would turn into hundreds of lines of Javascript and shader code, a Three.js requires only a tiny bit of code.

The goal of this section is for three. js for introduction. We started by building the scene using rotating cubes. If you encounter difficulties and need help, there is source code for reference at the bottom of the page.

At least three types of components required for a scene

  • Camera/Deciding what will be rendered on the screen

  • Light source /They will have an impact on how materials are displayed and how materials are used when generating shadows

  • Objects/They are the main rendering formations in the camera perspective: boxes, spheres, etc.

Before you start

Save the following HTML code on your computer, include three.js in the js directory, and then open it in the browser

 
 <meta>
 <title>My first three.js app</title>
 <style>
  body { margin: 0; }
  canvas { width: 100%; height: 100% }
 </style>
 
 
 <script></script>
 <script>
  // Our Javascript will go here.
 </script>
 

The next code will be downloaded in the script tag

Create a sample scene

In order to use three.js for display, we need three elements: scene, camera, renderer , in order to render the scene from the camera.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

Let's take a moment to explain what's going on. We have now created the scene, camera and renderer.

There are several types of cameras in three.js. We are temporarily using PerspectiveCamera

Its first attribute is the view angle (FOV), which is the visible view range, and its value represents the angle size.

The second attribute is the aspect ratio. Most of the time you want to use the width divided by the height, otherwise you end up with something like old movies on a widescreen TV - the image looks squashed.

The last two attributes are the near view surface and the distant view surface. Only the area between these two faces will be rendered. You don't need to worry about this for now; using these parameters can improve performance.

Next let’s talk about the renderer. This is the magic. In addition to the WebGLRenderer we use here, three.js also provides some renderers for use on older browsers that do not support WebGL.

In addition to creating a renderer instance, we also need to set the size of the application rendering. It is recommended to use a method that fills the entire width and height of the application - in this case, the width and height of the browser window. For performance-first applications, you can use setSize to set smaller values, such as window.innerHeight/2, window.innerWidth/2, which will render half the size.

If you want to render the entire size at low resolution, you can set the third parameter of setSize - uodateStyle to false if the canvas element is wide If the high value is 100%, the application will be rendered at 1/2 resolution.

Now, we need to add rendered elements to the HTML. The renderer shows us the scene through canvas.

"That's all good, but what about the cube I mentioned earlier" Let's add it now.

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

We need BoxGeometry to create the cube. This object contains all the points (vertices) and fills (faces) of the cube. We'll discuss that later.

In addition to the geometry, we also need materials to color it. three.js provides some materials, but we will use MeshBasicMaterial for now. All materials accept and apply an object containing all properties. For simplicity, we only provide one color attribute: green - 0x00ff00 . Uses the same hexadecimal colors as in CSS and PS.

The third element we need is Mesh. A mesh is an object that applies a material to geometry, which we can then place into the scene and move around freely.

When we call scene.add(), what we add will be displayed at coordinates (0, 0, 0,) by default. This causes the camera and cube to overlap internally. To avoid this, we simply move the camera a little further out.

Rendering scene

If you copy the above code in the HTML file, nothing will be displayed on the screen. Because we haven't rendered the scene yet. So we need to call the renderer or animation loop.

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

This creates a loop that has the renderer draw one frame every second. If you don't know much about web game programming, you might say "Why not write a setInterval function?" In fact, we can, but requestAnimationFrame has more benefits. The most important benefit is that requestAnimationFrame pauses rendering when the browser switches to another tab, so precious processing power and battery life are not wasted.

Let the cube move

If you insert the code we just created, you should see a green cube. Let it spin so it doesn't get boring.

Add the following code to renderer.render in the animate function:

cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

它会按帧运行(每秒60帧),并赋予立方体优雅的动画。基本上,应用运行时,你想移动或改变任何元素,必须通过动画循环。你当然在此处能调用其他函数,以免animate函数上百行代码结尾。

结果

恭喜!你现在创建好了第一个 three.js 应用。很简单,但总得突破。

完整代码参考如下。琢磨一下并深刻理解其工作机理

 
 <title>My first three.js app</title>
 <style>
  body { margin: 0; }
  canvas { width: 100%; height: 100% }
 </style>
 
 
 <script></script>
 <script>
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

  var renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  var cube = new THREE.Mesh( geometry, material );
  scene.add( cube );

  camera.position.z = 5;

  var animate = function () {
  requestAnimationFrame( animate );

  cube.rotation.x += 0.1;
  cube.rotation.y += 0.1;

  renderer.render(scene, camera);
  };

  animate();
 </script>
 

相关推荐:

three.js通过模块导入实例分享

three.js如何本地运行详解

实例讲解Three.js加载外部模型

The above is the detailed content of Detailed explanation of creating scene instances with three.js. 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.