What are the three. Js

Three js encapsulates the underlying graphics interface, allows the programmer to without knowledge of onerous graphics, simple code can also be used to realize 3 d scene rendering, relative to the webGL, Three. Js encapsulate the underlying graphical interface, in the case of don’t know about graphics, simple code can also be used to realize 3 d scene rendering

Preview the address

Begin to use

Introduced the CDN

 <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/109/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
Copy the code

Create an environment

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

  • Scene A space container in which all objects are placed, three-dimensional space. Simply new a Scene class to create an instance that calls the 3D Scenenew scene = new THREE.Scene()
  • Camera three.js adopts the right-handed coordinate system

PerspectiveCamera simulates the real world in human eyes more realistically, which is also used in this example

PerspectiveCamera(fov, aspect, near, far)

Its constructor takes four different arguments, all of type Number

Fov -- Vertical field of vision aspect of camera cone -- length-width ratio of camera cone NEAR -- far near end of camera cone -- far end of camera coneCopy the code

Var camera = new THREE.PerspectiveCamera(75,// view aspect ratio window.innerwidth/window.innerheight,// view aspect ratio window.innerwidth/window.innerheight 1000,// Remote distance far) // Set the camera position on the z axis camera.position.z = 5;Copy the code
  • Renderer (the Renderer) Renderer with webGL | CSS2d | CSS3d | SVG, among them the most flexible and powerful webGL
var renderer = new THREE.WebGLRenderer({
    antialias: true, // Whether anti-aliasing. The default isfalse/* canvas: canvas, // The canvas to which the renderer draws its output. If this parameter is not passed, a new canvas precision is created:'highp'Precision, / / shader. Highp | mediump | lowp | highp (default) alpha: flase, / / canvas does it include the alpha (transparency). The default isfalseStencil: flase // Whether the drawing cache has a template cache. The default istrue
     */
    });
 renderer.setClearColor("#e5e5e5");
 renderer.setSize(window.innerWidth,window.innerHeight);

Copy the code

Created after the dom structure generated from the renderer (a tag) is append to the HTML document. The body. The appendChild (the renderer. DomElement accordingly);

Create an object

Many types of objects are provided in Three.js, which inherit from Object3D class, including Line, Bone, and ParticleSystem. The most common one is Mesh, which is an object composed of vertices, edges and faces. The more the Mesh, the smoother the surface of the object, which is closer to imitating the real.

Every object has a shape, a material

  • There are so many kinds of shapes… Circles, spheres, columns, columns, text shapes… A variety of arbitrary, but are simple basic models, complex models or need to import, support import *.obj external model
  • Material is a rendering property that is independent of the object’s vertex information. You can change the color, texture map and lighting mode of the object by setting the material. Here we use the Lambert material (MeshLambertMaterial), which conforms to the Lambert lighting model. The main characteristic of Lambert illumination model is that it only considers diffuse reflection without considering specular reflection effect, which is applicable to most objects.
Var geometry = new THREE.BoxGeometry(1, 1, 1); / / radius, width, smooth degree of var material = new THREE. MeshLambertMaterial (xf7f7f7} {color: 0); Var MESH = new THREE. (Geometry, material);Copy the code

I have the scene and object, and when I open the browser, I see a dark ugly square, which seems to be different from 3D.

Three. Js provides a variety of light sources, including AmbientLight, PointLight, SpotLight, DirectionalLight, HemisphereLight, and so on. Just add the required light source to the scene, plus a certain amount of object rotation. I’m using PointLight here,

var light = new THREE.PointLight(0xffffff, 1, 500); Light.position. set(0,0,10); // Set the light position scene.add(light); Mesh. Rotation. The set (45,45,0);Copy the code

Then the model on the page looks like this

animation

There are many dynamic effect libraries. Here we use the TimelineMax plug-in for complex animation sequences using GASP (Green Sock). Please refer to the Tweenmax Chinese manual in the document

Add ray

The browser is a 2D viewport, and the content displayed in three.js is a 3D scene, so there is a problem of converting the X and Y coordinates of the 2D viewport to the 3D coordinates of the three.js scene. Three. js already has a solution to this problem with the three. Raycaster ray, which is used by the mouse to retrieve objects selected by the mouse in the 3D world

Var rayCaster = new three.raycaster (); var mouse = new THREE.Vector3();Copy the code

Raycaster uses the case Raycaster in the official documentation

TweenMax API

  • .to( target, duration, vars, position)
parameter type instructions
target Object The object that needs to be animated
duration Number The number of seconds (or frames) the animation lasts
vars Object Animation parameters (CSS properties, delays, repetitions, etc.)
position Insert the position of the animation
  • Ease: speed curve of transition effect (ease effect), set various eases in the parameters of the animation to control the rate of change of the animation, Expo: special ease
 functiononMouseMove(event){ event.preventDefault(); // Normalize mouse position to device coordinates. X and Y directions range from (-1 to +1) mouse. X = (Event.clientx/window.innerWidth) * 2-1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; // Update raycaster. SetFromCamera (mouse, camera); / / calculate the focus of the objects and ray var intersects. = raycaster intersectObjects (scene. The children,true);
          for(leti = 0; i<intersects.length ; I++){this.tl = new TimelineMax().delay(.3); Tl. To (Intersects [I].object.scale, 1, {x:2, ease: EaseOut})// this.tl. To (intersects[I].object.scale,.5, {x:.5, ease: Expo.easeOut}) this.tl.to(intersects[i].object.position, .5, {x:2, ease: Expo.easeOut}) this.tl.to(intersects[i].object.rotation, .5, {y:Math.PI*.5, ease: Expo.easeOut},"=-1.5"}} render(); // Add the listener event window.addeventListener ('mousemove', onMouseMove)
Copy the code

At this point you can see that the object is already moving

Effect of implementation

It can be seen that the final effect is to randomly create one model after another and scatter them on the page. Therefore, multiple models are created in a cycle here, and the “oncoming” animation effect is achieved by changing their position on X, Y and Z by random

    meshCount = 0;
    for( var i = 0 ; i < 20 ; i++) { var mesh = new THREE.Mesh(geometry, material); Mesh.position.x =(math.random () -0.5) *10; Y =(math.random () -0.5) *10; Mesh.position. z =(math.random () -0.5) *10; scene.add(mesh); meshCount++; }Copy the code

Can see light is not enough at this time, need to add a illuminant again, the position coordinate of illuminant, intensity, distance, decline quantity can adjust according to oneself feeling

var light = new THREE.PointLight(0xffffff, 1, 1000); Light.position. set(0,0,0); scene.add(light);Copy the code

The effect of multiple random models is shown in figure

responsive

Automatically resize the rendered model by browser size

// Listen for window changes while updating window.adDeventListener ('resize',()=>{ renderer.setSize(window.innerWidth,window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; / / note that the last must call updateProjectionMatrix update () method of the camera. The updateProjectionMatrix (); }) // Finally render var render =function(){// requestAnimationFrame(render) does not affect the width of the browser; renderer.render(scene,camera); }Copy the code

Add a title at the end and you’re done

The last

Reference:

TimelineMax Chinese Handbook

Three. Js document

A guide to getting started with Three.js

In addition to official documents and cases, I can learn three.js’s guide to people. Sister Xianzhe is the first person I follow on GitHub. I like her very much

It is the first time to send an article in nuggets