当前位置:网站首页>Use threejs simple Web3D effect

Use threejs simple Web3D effect

2022-07-01 08:08:00 CK continues to grow

Catalog

1. threejs Introduce

2. thresjs Use

3. Component is introduced

4. threejs Animation

5. Reference material


I saw one on the Internet a few days ago threejs Implementation of web 3d Animation , It's cool , So I made a special trip to find out threejs. Let's first look at the official use threejs To achieve the effect of :

 

1. threejs Introduce

threejs It's based on the original WebGL API And shader encapsulation 3D engine , That's one .js library . Directly through the original WebGL Write programs directly , It's a little bit of a hassle , therefore threejs That's right WebGL Made a layer of encapsulation , It's so convenient web Start developing web 3d Application .

therefore WebGL yes threejs The basis of , Simple projects don't usually use the bottom layer WebGL knowledge , But learning WebGl Helps to understand threejs, If you use Three.js When a development project needs custom shaders , Must also be to learn from the bottom WebGL And shaders GLSL knowledge .

2. thresjs Use

First, let's take a look at the example effect we have achieved , Realize a cylinder that can be operated by the mouse :

Code implementation :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>My first three.js app</title>
    <style>
        body { margin: 0; }
    </style>
</head>
<body>
<script src="js/three.js"></script>
<script src="js/OrbitControls.js"></script>
<script>

    /**
     *  Scene object creation 
     */
    const scene = new THREE.Scene();
    
    /**
     *  Cube geometry objects Geometry
     */
    const geometry = new THREE.BufferGeometry(); // Create a Buffer Type geometry object 
    // Type array to create vertex data 
    const vertices = new Float32Array([
        0, 0, 0,        // The vertices 1 coordinate 
        50, 0, 0,       // The vertices 2 coordinate 
        0, 100, 0,      // The vertices 3 coordinate 
        0, 0, 10,       // The vertices 4 coordinate 
        0, 0, 100,      // The vertices 5 coordinate 
        50, 0, 10,      // The vertices 6 coordinate 
    ]);
    //  Create an attribute buffer object 
    const attribue = new THREE.BufferAttribute(vertices, 3); //3 One for a group , Representing a vertex xyz coordinate 
    //  Set up the geometry attributes The location of the property 
    geometry.attributes.position = attribue;

    /**
     *  Material object 
     */
    const material = new THREE.MeshBasicMaterial({
        color: 0x0000ff,            // Triangle color 
        side: THREE.DoubleSide      // You can see it on both sides 
    });

    /**
     *  Mesh model objects Mesh, Construction through geometric objects and materials of geometric objects 
     */
    const cube = new THREE.Mesh(geometry, material);
    scene.add( cube );
    
    /**
     *  Auxiliary coordinate system    Parameters 250 Represents the size of the coordinate system , It can be set according to the scene size 
     */
    var axisHelper = new THREE.AxesHelper(250);
    scene.add(axisHelper);

    /**
     *  Lighting settings 
     */
    // Point source 1
    var point = new THREE.PointLight(0xffffff);
    point.position.set(400, 200, 300); // Position of point light source 
    scene.add(point); // Add point lights to the scene 
    //  Point source 2   Location and point About the origin symmetry 
    var point2 = new THREE.PointLight(0xffffff);
    point2.position.set(-400, -200, -300); // Position of point light source 
    scene.add(point2); // Add point lights to the scene 
    // The ambient light 
    var ambient = new THREE.AmbientLight(0x444444);
    scene.add(ambient);

    /**
     *  Camera settings 
     * @type {PerspectiveCamera}
     */
    var width = window.innerWidth;              // Window width 
    var height = window.innerHeight;            // Window height 
    var k = width / height;                     // Window aspect ratio 
    var s = 500;                                // Three dimensional scene display range control coefficient , The larger the coefficient , The larger the scope of the display 
    // Create camera objects 
    const camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    // const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    camera.position.set(200, 300, 200);             // Set camera position 
    camera.lookAt(scene.position);                  // Set camera orientation ( Point to the scene object )
    // camera.position.z = 5;

    /**
     *  Renderers 
     */
    /* WebGLRender */
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor(0xb9d3ff, 1); // Set the background color 
    document.body.appendChild( renderer.domElement );

    /**
     *  Manual operation 
     * */
    function render(){
        renderer.render(scene,camera);
    }

    render()

    var controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', render);// Monitor the mouse 、 Keyboard events 
</script>
</body>
</html>

Detailed comments have been added to the code , Let's mainly talk about the main composition :

  • 1. scene (Scene) constitute : The scene is mainly divided into grid models (Mesh) And light source (Light). Mesh model is mainly used to construct the geometry structure in the scene , We can build a whole frame structure with various geometric problems , The material is more like web Style in , Build color for Geometry , Transparency, etc. . The other is the light source , The light source is equivalent to that we add light and shade to the above mesh model , When we add a stronger light source to it , It should be brighter . stay 3D In structure , Different lighting has different shading effects , To show the three-dimensional sense of space . In the code, we create the corresponding grid model Mesh And light source (Light), Add to Scene To build
  •   The camera (Camera): The camera mainly provides a perspective for the mechanism in the scene . The scenario has been built as 3D Model of , and 3D The structure is a three-dimensional scene , The human eye can't see every side in a straight line , So what we offer here Camera It provides a viewing angle , Through different camera angles , We can go from different places , See different directions of the three-dimensional structure from different directions of the line of sight , The effect of different distances . It's like we actually use cameras , We're going to take a picture , You need to choose different positions and angles .
  • Renderers (Render):   Through the above scenes and cameras, we have built a virtual three-dimensional scene , The position and angle of the camera are also set , Then the rest is to take photos . Taking pictures is like taking pictures in two dimensions web Display on the plane 3D The stereoscopic effect of a picture in a certain angle of view . When we change our perspective , The renderer will not have different projection effects .

Refer to the rendering process diagram at the end of the following text :

3. Component is introduced

    We already know about it threejs A construction process and rendering process . With the example above , The composition of the whole program is shown in the figure below ( Reference pictures ):

  In the example above , We built a..., using these components threejs Of 3d application , And the follow-up study is mainly carried out around each structure in the component .

4. threejs Animation

threejs There are two kinds of animation : 1. api Periodic animation provided ,2. Animation based on manual operation

api The cycle animation provided is mainly by cycle , Refresh or change some attributes regularly , Such as rotation angle . We can use js Timer implementation , You can also use requestAnimationFrame The implementation of the .

Animation based on manual operation , Mainly in response to the use of user operations , According to the result of user operation , To transform and refresh certain attributes . For example, in the example above , We use an action that responds to actual user actions , The object will rotate according to the actual drag . Above we use an operation library provided by the official example :

https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js

5. Reference material

Official documents : https://threejs.org

threejs Chinese net : Three.js course

原网站

版权声明
本文为[CK continues to grow]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010805230936.html