About WebGL

WebGL is a Web standard based on OpenGL ES 2.0 and can be accessed through the HTML5 Canvas element as a DOM interface.

What are the THREE. Js

Three.js is a WebGL third-party library written in JavaScript. Three.js encapsulates the graphical interface at the bottom of WebGL, and developers can use simple JS codes to achieve 3d scene rendering without having to master graphics knowledge. When rendering the 3D model, it is actually made up of many triangles. As follows:

On the left is a cube, and on the right is a sphere (for spheres, the more triangles cut out, the closer the mesh will be to the sphere);

The core code is as follows

// Cube (X-axis width, Y-axis height, Z-axis depth, number of segments along the width plane, number of segments along the height plane, number of segments along the depth plane)
object = new THREE.Mesh(
  new THREE.BoxGeometry(100.100.100.1.1.1),
  material
);
object.position.set(- 200..0.- 200.);
scene.add(object);

// Cube (X-axis width, Y-axis height, Z-axis depth, number of segments along the width plane, number of segments along the height plane, number of segments along the depth plane)
object = new THREE.Mesh(
  new THREE.BoxGeometry(100.100.100.2.2.2),
  material
);
object.position.set(- 200..0.200);
scene.add(object);

// Spherical mesh (radius length, density of horizontal blocks, density of vertical blocks)
var object = new THREE.Mesh(new THREE.SphereGeometry(75.5.5), material);
object.position.set(200.0.- 200.);
scene.add(object);

// Spherical mesh (radius length, density of horizontal blocks, density of vertical blocks)
var object = new THREE.Mesh(new THREE.SphereGeometry(75.50.50), material);
object.position.set(200.0.200);
scene.add(object);



Copy the code

Three important objects, scenarios, in a three.js projectscene,camerarenderer

A typical three. js program should include at least the Renderer, Scene, Camera, and the objects you create in the Scene.

  • Scene: Objects added to three.js are added to the scene, so it acts as a large container.
  • Renderer: a renderer that mounts a Canvas tag for final rendering
  • -Lily: What’s the camera?

Renderer. render(scene, camera);

Before we look at these three objects, we need to know a little bit about themthree.jsThe coordinate system of

WebGL and three.js use a right-handed coordinate system that looks something like this:

The basic steps to create a three.js project are as follows

1. Create a scenarioscene

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

Copy the code

2. Create cameracamera

Two kinds of cameras, orthogonal camera and perspective projection camera

Generally speaking, orthogonal projection is usually used for mapping and modeling software, so as not to change the scale of the object because of projection; For most other applications, perspective projection is usually used because it is closer to the human eye.

Figure A below is a perspective projection (near larger and far smaller, more realistic), and Figure B is an orthogonal projection

Orthogonal camera

OrthographicCamera(left, right, top, bottom, near, far);

  • These six parameters respectively represent the positions of the six faces of the space photographed by the orthogonal projection camera. The two faces are enclosed in a long square body, which we call the Frustum. Only objects inside the viewport (gray in the image below) can be displayed on the screen, while objects outside the viewport are clipped before being displayed.
  • To maintain the camera’s vertical ratio, make sure that the right-left and top-bottom ratio is the same as the Canvas width and height ratio.

The creation method is as follows:

var camera = new THREE.OrthographicCamera(2 -.2.1.5.1.5.1.10);
camera.position.set(0.0.5);
scene.add(camera);
Copy the code

Perspective projection camera

PerspectiveCamera(fov, aspect, near, far)

  • Fov is the Angle of the view vertically (in angles rather than radians), as shown in the side view.
  • Aspect is equal to width/height, which is the ratio of the horizontal and vertical lengths of the camera, usually set as the horizontal and vertical ratio of the Canvas.
  • Near and FAR are the nearest and furthest distances from the camera to the scene, respectively. They are both positive values, and FAR should be greater than NEAR.

In the perspective, the gray part is the viewframe, which is the area of the object that might be rendered.

Create it as follows

var camera;
function initCamera(){
    camera = new THREE.PerspectiveCamera( 75.window.innerWidth / window.innerHeight, 0.1.1000 );
}

Copy the code

3. Create the rendererrenderer

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

Copy the code

4. Create a grid model

var geometry = new THREE.BoxGeometry(1.1.1);
var matrial = new THREE.MeshBasicMaterial({color:0x00ff00});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
Copy the code

5. A simple demo

Knowing the above key is to start rendering a simple 3D scene

var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; Var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(windowWidth, windowHeight); document.body.appendChild(renderer.domElement); Var scene = new three.scene (); var scene = new three.scene (); PerspectiveCamera = new THREE.PerspectiveCamera(45, windowWidth/windowHeight, 1, 400); camera.position.set(0, 0, 3); Var light = new THREE.AmbientLight("#ffffff");
light.position.set(0, 0, 1);
scene.add(light);

var map = new THREE.TextureLoader().load("./img/lala.jpg"); Var Material = new THREE.MeshPhongMaterial({map: map}); // The geometry of a cube is new THREE. Var cube = new THREE.Mesh(Geometry, Material); scene.add(cube); (function animateRenderer. render(scene, camera); Cube. Rotation. X + = 0.02; Cube. Rotation. + y = 0.02; requestAnimationFrame(animate); }) ();Copy the code

Common configuration objects:

The material

Basic materialsMeshBasicMaterial

For objects with basic materials, the rendered color will always be the same as the set color, that is, it will not be affected by lighting, such as the sun is useful, when not set color, the color will be random

The constructor is THREE.MeshBasicMaterial(opt);

// Example (create a yellow material with an opacity of 0.75)
var  geometry = new THREE.SphereGeometry(3.30.30);
var map =  new THREE.TextureLoader().load('./img/lala.jpg');
var material = new THREE.MeshBasicMaterial({
   color:0xffff00.opacity:0.75
})

var cube = new THREE.Mesh(geometry, material)

Copy the code

MeshLambertMaterial andMeshPhongThe material

THREE. MeshLambertMaterial (opt) with THREE. MeshPhongMaterial (opt) and THREE basic materials. MeshBasicMaterial (opt) is to use consistent approach. Several of their common attributes (default values after commas)

  • Visible: Indicates whether the device is visible, true
  • Side: Render the front or back of the surface. Default is THREE.FrontSide
  • Wireframe: whether to render as lines instead of faces, default is false,
  • Color: hexadecimal color (0xffFFFF)
  • Map: Use a texture map, such as (new three.textureLoader ().load(‘./img/lala.jpg’);

The difference is that under light, Lambert model is diffuse reflection, which is more suitable for most situations in life, while Phong model is suitable for metal and mirror objects with relatively high reflectivity

  • Phong shader

  • Lambert material

Light

// Ambient light can be observed from all angles
var light = new THREE.AmbientLight("#0000ff");
light.position.set(0.0.1);
scene.add(light);

// Point light source, as the name implies
spotLight = new THREE.PointLight("#ffffff");
spotLight.position.set(0.0.0);
scene.add(spotLight);

// Parallel light, as the name implies
directionalLight = new THREE.DirectionalLight("#ffffff");
directionalLight.position.set(- 40.60.- 10);
// Tell parallel light to enable shadow casting
directionalLight.castShadow = true;
scene.add(directionalLight);

Copy the code

Load external models, such asstlformat

<! STL loaders need to be introduced first, other similar -->
	<script src="./lib/STLLoader.js"></script>
Copy the code
function initModel() {

  // Auxiliary tools
  var loader = new THREE.STLLoader();
  loader.load("./model/aixiaofei.stl".function(geometry) {
    // Create a texture
    new THREE.TextureLoader().load("./img/lala.jpg".function(map) {
    var material = new THREE.MeshPhongMaterial({
        color:0xffffff.map: map
      });

      var mesh = new THREE.Mesh(geometry, material);
      mesh.rotation.x = 0.5 * Math.PI; // Align the model
      mesh.scale.set(0.1.0.1.0.1); / / zoom
      geometry.center(); // Center display
      scene.add(mesh);
    });
  });
}
Copy the code

example

  1. The solar system

  1. VR