[Three.js] Chapter 3 Scene Basic Scene

03.Basic scene basic scene

introduce

In our first lesson, we'll make it Three.jswork in the most straightforward way possible: no bundlers, no dependencies, no modules, just HTMLa JavaScript.

basic document

First, create a normal index.htmlfile:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>03 - Basic Scene</title>
</head>
<body>
    <script src="./script.js"></script>
</body>
</html>

and a simple script.jsfile:

console.log('Hello Three.js')

Now open the developer tools.
Then navigate to the tabs at Developer Toolsthe top . You should always keep the console open to view potential errors and warnings.Console

How to load Three.js

Now we need to load Three.jsthe library. There are many ways to do this. Now, we will simply download the library and use it.
Go to https://threejs.org/ click the download button to download the zip file and unzip it. The files are huge, but don't worry, we only need one of them.
You should end up with a folder that looks like this:

go to build/the folder and three.min.jscopy the file to your project.
You should get something like this:

we can now load Three.jsthe library at the end:

<script src="./three.min.js"></script>
<script src="./script.js"></script>

Make sure to load it three.min.jsbefore script.js; otherwise, script.jsthe script in the file will be executed first, and three.min.jsthe contents of the file will not be known.

How to use Three.js

In our script.jsfile, we have access to a THREEvariable named . Note that it must be written in capital letters.
If you look console.log()at this variable, you will find that there are many attributes in it:

console.log(THREE)

image.png
This THREEvariable contains Three.jsmost of the classes and properties that may be needed in a development project. Unfortunately, not all classes are in this variable, but we'll teach how to access and use them later.
To use one of these classes, you need to instantiate it. For example, if you wanted to create a scene, you would write const scene = new THREE.Scene(). If you wanted to create a sphere geometry, you would write const sphereGeometry = new THREE.SphereGeometry(1.5, 32, 32)- we'll dig into these in more depth later.

first act

Time to create our scene and make something on screen.
We need 4 elements to get started:

  1. scene containing objects
  2. some model objects
  3. camera
  4. Renderer

SceneScene _

A scene is like a container. You put objects, models, particles, lights, etc. into it, and at some point ask Three.jsthe scene to be rendered.
To create a scene, use the Scene class:

// Scene
const scene = new THREE.Scene()

Object Mesh

Objects can be many things. Includes original geometry, imported models, particles, lights, and more.
We'll start the design with a simple red cube.
To create the red cube, we need to create a type of object called a Mesh . A mesh is a combination of geometry (shape) and material ( appearance).
There are many types of geometry and materials, but we will simply create a BoxGeometry and a MeshBasicMaterial for now .
To create the geometry, we use the BoxGeometry class, whose first 3 parameters correspond to the size of the box.

// Object
const geometry = new THREE.BoxGeometry(1, 1, 1)

In order to create a material, we need to use the MeshBasicMaterial class with one parameter : an {}*object containing all options. We can specify its colorproperties first. There are several ways of specifying colors in
. Three.jsYou can enter it as a JS hexadecimal 0xff0000, you can enter it as a string hexadecimal '#ff0000', or you can use a color name, such as entering Color 'red' - more on that later.

// Object
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({
    
     color: 0xff0000 })

To create the final mesh we use the Mesh class and write the **geometry**and **material**parameters.

// Object
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({
    
     color: 0xff0000 })
const mesh = new THREE.Mesh(geometry, material)

Meshes can now add(...)be added to the scene using:

scene.add(mesh)

If you do not add a mesh object to the scene scene, then this object cannot be rendered.

CameraCamera

The camera is not visible. This is more of a theoretical point of view. When we render the scene, it will be rendered from the perspective of this camera .
You can abstract it as a camera in a movie scene, so three.jsyou can have multiple cameras , and you can switch between these cameras as needed . Usually, we only use one camera.
There are different types of cameras and we will discuss these in a later lesson. Now, we just need a camera that handles perspective (making close objects look more prominent than distant ones).
To create a camera, we use the PerspectiveCamera class.
We need to provide two basic parameters to this class.
Parameter 1: Field of view Field of view
is how big your viewing angle is. If you use very large angles, you will be able to see all directions at the same time, but it will be distorted because the result will be drawn on a small rectangle. If you use small angles, things will look magnified. The field of view (or fov ) is expressed in degrees and corresponds to the vertical viewing angle. For this exercise, we will use an angle of 75 .
Parameter Two: Aspect Ratio
In most cases, the aspect ratio is the width of the canvas divided by its height . We haven't specified any width or height yet, but we'll need to later. At the same time, we will create an object with a temporary value that can be reused.
Don't forget to add the camera to the scene . In case the camera is forgotten to be added to the scene, it may cause an error later:

// Sizes
const sizes = {
    
    
    width: 800,
    height: 600
}

// Camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height)
scene.add(camera)

Renderer WebGLRenderer

The renderer's job is to render .
We will simply ask the renderer to render our scene from the camera's point of view , and the result will be drawn into the canvas . You can create the canvas yourself , or let the renderer generate it and add it to your page . For this exercise, we'll add the canvas to htmland JavaScriptbind it to the renderer by getting the element node. Create the element before
loading the script and give it a :<canvas>class

<canvas class="webgl"></canvas>

To create the renderer, we use the WebGLRenderer class with one parameter : an {}object containing all the options. We need to specify canvasvariables that correspond to our <canvas>labels.
Create a variable canvas, then take the label created using in document.querySelector(...)and store it in it. It's best to assign the canvas to a variable, as we'll use this variable to manipulate elements in the next lesson . Method: We also need to update the size of the renderer using the method of the object created earlier . The method will automatically resize us accordingly :HTML<canvas>
DOM
setSize(...)sizessetSize(...)<canvas>

// Canvas
const canvas = document.querySelector('canvas.webgl')

// ...

// Renderer
const renderer = new THREE.WebGLRenderer({
    
    
  canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)

Right now, we still can't see anything, but the canvas is there and has been resized accordingly. You can use the developer tools to check <canvas>the size.

render first

Time to start our first render. render(...)Call the method on the renderer and send it the sceneand cameraparameters:

renderer.render(scene, camera)

Still no? The problem is: we didn't specify the position of the object, nor the position of the camera. Both are in the default position, which is the center of the scene, and we cannot see the overall appearance of the object from the inside of the solid object (by default).
We need to move objects.
To do this, we can access multiple properties of each object, such as position, , rotationand scale. Now, use positionthe properties to move the camera backwards.
The positionproperty is an object with three related properties: x, yand z. By default, Three.js considers the forward/backward axis to be z.
To move the camera backwards, we need to provide a positive value for this property. Once you create camerathe variable, you can use it anywhere, but it must be used before you render:

const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height)
camera.position.z = 3
scene.add(camera)


Congratulations, we've seen the first rendered work. It looks like a square, and that's because the camera is perfectly aligned with the cube, and you can only see one side of it.
Don't worry about the size of the render; we'll learn how to fit the canvas to the viewport later.
In the next lessons, you'll learn more about the position, , rotationand properties, and how to change them and animate the scene.scale

Guess you like

Origin blog.csdn.net/m0_68324632/article/details/130790383