当前位置:网站首页>Three. JS import model demo analysis (with notes)
Three. JS import model demo analysis (with notes)
2022-06-12 04:44:00 【Dyz_ quite】
demo source ( If you find it useful, please like it , If the collection is better Thank you )
This issue is github Pull Three.js Introduction of pairs in source code glb Format model demo analysis
clone Address :[email protected]:mrdoob/three.js.git
demo Catalog :examples\webgl_animation_keyframes
The source code is as follows ( Below I will analyze the source code one by one )
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - animation - keyframes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
<style>
body {
background-color: #bfe3dd;
color: #000;
}
a {
color: #2983ff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - animation - keyframes<br />
Model: <a href="https://artstation.com/artwork/1AGwX" target="_blank" rel="noopener">Littlest Tokyo</a> by
<a href="https://artstation.com/glenatron" target="_blank" rel="noopener">Glen Fox</a>, CC Attribution.
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import Stats from './jsm/libs/stats.module.js';
import {
OrbitControls } from './jsm/controls/OrbitControls.js';
import {
RoomEnvironment } from './jsm/environments/RoomEnvironment.js';
import {
GLTFLoader } from './jsm/loaders/GLTFLoader.js';
import {
DRACOLoader } from './jsm/loaders/DRACOLoader.js';
let mixer;
const clock = new THREE.Clock();
const container = document.getElementById( 'container' );
const stats = new Stats();
container.appendChild( stats.dom );
const renderer = new THREE.WebGLRenderer( {
antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.outputEncoding = THREE.sRGBEncoding;// texture of material
container.appendChild( renderer.domElement );
const pmremGenerator = new THREE.PMREMGenerator( renderer );
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xbfe3dd );
scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture;
const camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 100 );
camera.position.set( 5, 2, 8 );
const controls = new OrbitControls( camera, renderer.domElement );
// controls.target.set( 0, 0.5, 0 );
controls.update();
controls.enablePan = false;
controls.enableDamping = true;
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( 'js/libs/draco/gltf/' );
const loader = new GLTFLoader();
loader.setDRACOLoader( dracoLoader );
loader.load( 'models/gltf/Horse.glb', function ( gltf ) {
const model = gltf.scene;
model.position.set( 1, 1, 0 );
model.scale.set( 0.01, 0.01, 0.01 );
scene.add( model );
mixer = new THREE.AnimationMixer( model );
mixer.clipAction( gltf.animations[ 0 ] ).play();
animate();
}, undefined, function ( e ) {
console.error( e );
} );
window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
};
function animate() {
requestAnimationFrame( animate );
const delta = clock.getDelta();
mixer.update( delta );
controls.update();
stats.update();
renderer.render( scene, camera );
console.log( delta );
console.log( mixer.update( delta ) );
}
</script>
</body>
</html>
demo design sketch

Code by code analysis
Import three library
import * as THREE from 'three';
Import a performance view plug-in This thing will not be used in the project , Used to analyze
This thing is in the upper right corner of the rendering Here's the picture
import Stats from './jsm/libs/stats.module.js';

Import a Track controller : Also known as camera angle controller ( The specific use will be described below )
import {
OrbitControls } from './jsm/controls/OrbitControls.js';
Import the material file of the model .
import {
RoomEnvironment } from './jsm/environments/RoomEnvironment.js';
Import the required... For the model format respectively loader file . If you need to import other model formats , It can be found in the git Source code found in
import {
GLTFLoader } from './jsm/loaders/GLTFLoader.js';
import {
DRACOLoader } from './jsm/loaders/DRACOLoader.js';
Create a clock object Clock**( Will be used for demo Car movement in )**
const clock = new THREE.Clock();
Here we get container Elements . And assigned to the variable container
new A plug-in for performance checking Added to the element
const container = document.getElementById( 'container' );
const stats = new Stats();
container.appendChild( stats.dom );
Set up three Rendered as webGL And assigned to the variable renderer
Yes renderer See notes for detailed settings of
const renderer = new THREE.WebGLRenderer( {
antialias: true } );
// Pixel ratio setting
renderer.setPixelRatio( window.devicePixelRatio );
// Render container size settings
renderer.setSize( window.innerWidth, window.innerHeight );
// When importing materials , The map encoding format is defined as... By default Three.LinearEncoding, Therefore, it is necessary to manually specify the color information as Three.sRGBEncodin
renderer.outputEncoding = THREE.sRGBEncoding;// texture of material
take randerer Element added to container in .
Generate a brightness environment , Pass in renderer And assigned to pmremGenerator
Scene: Generate a scene object .
Set up scene The background color of the scene object
// Add a render container to html In the box
container.appendChild( renderer.domElement );
const pmremGenerator = new THREE.PMREMGenerator( renderer );
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xbfe3dd );
The imported model is used here .RoomEnvironment.js File interested students can analyze the file directory as follows
examples\jsm\environments
import {
RoomEnvironment } from './jsm/environments/RoomEnvironment.js';
...
...
scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture;
Next, set up the camera
PerspectiveCamera Function common 4 Parameters All data types are number
PerspectiveCamera( fov, aspect, near, far );
- fov——fov Indicates the field of view , The so-called field of view is the angle range that can be seen , Human eyes can see about 180 Degree field of view , The viewing angle size should be set according to the specific application , The general game will set 60~90 degree . The default value is 45
- aspect——aspect Represents the aspect ratio of the rendering window , If there is only one full screen on a web page canvas Canvas and there is only one window on the canvas , that aspect The value of is the aspect ratio of the client area of the web page window window.innerWidth/window.innerHeight
- near——near Property indicates how far away from the camera to start rendering , Generally, a small value will be set . The default value is 0.1
- far——far Property indicates how far away from the camera the rendering is , If the set value is too small , There will be some scenes that you can't see . The default value is 1000
new One PerspectiveCamera Set the parameter and set its initial viewing angle
Down OrbitControls Imported generic OrbitControls Camera controller and set its attribute value
const camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 100 );
camera.position.set( 5, 2, 8 );
const controls = new OrbitControls( camera, renderer.domElement );
controls.update();
// Whether to disable right-click dragging
controls.enablePan = false;
controls.enableDamping = true;
Daoru loader Model . Every step of the code has comments
loader.load Function to receive parameters , Ask separately . Model address . Rendering function , You can also receive error messages , Print it out to see the specific error
// Import DRACO Format loader
const dracoLoader = new DRACOLoader();
// Set up loader Path decompression compression model
dracoLoader.setDecoderPath( 'js/libs/draco/gltf/' );
// Import GLTF Format loader
const loader = new GLTFLoader();
// Set up DRACOloader
loader.setDRACOLoader( dracoLoader );
// Import
loader.load( 'models/gltf/LittlestTokyo.glb', function ( gltf ) {
const model = gltf.scene;
model.position.set( 1, 1, 0 );
model.scale.set( 0.01, 0.01, 0.01 );
scene.add( model );
mixer = new THREE.AnimationMixer( model );
mixer.clipAction( gltf.animations[ 0 ] ).play();
animate();
}, undefined, function ( e ) {
console.error( e );
} );
Animation execution function
repeat animate Function to get the time update renderer
function animate() {
requestAnimationFrame( animate );
// Obtain the time interval between the first and second execution of the method
const delta = clock.getDelta();
mixer.update( delta );
controls.update();
// Performance control update
stats.update();
renderer.render( scene, camera );
}
This concludes the full text
边栏推荐
- Mysql主从搭建与Django实现读写分离
- 1007- stair climbing
- Work report of epidemic data analysis platform [4] cross domain correlation
- 2022 examination questions and simulation examination for crane driver (limited to bridge crane)
- Longest palindrome string
- CCF access control system
- 1008 color classification
- What is reverse repurchase of treasury bonds? Is the reverse repurchase of treasury bonds safe?
- Encapsulation manuelle d'un foreach et d'une carte
- New year news of osdu open underground data space Forum
猜你喜欢

Legendary biological car-t has been approved by FDA, becoming the first domestic cell therapy product to successfully go to sea

Day17 array features array boundary array application traversal array multidimensional array creation and traversal arrays operation array bubble sort

Tasks in C #

图解 Apache SkyWalking UI 的使用

MySQL master-slave construction and Django implementation of read-write separation

Let me tell you the benefits of code refactoring

疫情数据分析平台工作报告【2】接口API

Operation of simulated examination platform for theoretical question bank of G2 utility boiler stoker in 2022

1. Mx6ull learning notes (II) - uboot migration

How to use union all in LINQ- How to use union all in LINQ?
随机推荐
mysqld: Can‘t create directory ‘D: oftinstall\mysql57 (Errcode: 2 - No such file or directory)
JWT学习与使用
These programming languages are worth learning
1009 word search
Operation of simulated examination platform for 2022 safety officer-b certificate examination questions
Detailed explanation of Command Execution Vulnerability
1007- stair climbing
Betteland introduces milk products of non animal origin, which will be launched in the U.S. market in the near future
Walking "daily question" and "DP"
疫情数据分析平台工作报告【4】跨域相关
1. Mx6ull learning notes (II) - uboot migration
What is reverse repurchase of treasury bonds? Is the reverse repurchase of treasury bonds safe?
加速训练之并行化 tf.data.Dataset 生成器
Oracle's instr()
Interview must ask: summary of ten classic sorting algorithms
L1-064 AI core code valued at 100 million (20 points)
WPF 数据绑定(四)
Bearpi IOT serial port transceiver 1- normal mode
Summary of common interview questions in redis
L1-065 "nonsense code" (5 points)