当前位置:网站首页>Use threejs to create geometry and add materials, lights, shadows, animations, and axes
Use threejs to create geometry and add materials, lights, shadows, animations, and axes
2022-07-05 04:00:00 【Zuo Ben】
1, Introduce :
This example uses r95 edition Three.js library . You will create a scene and add geometry , Add geometry dynamically , Delete Geometry , Add materials to geometry 、 The light source 、 Shadows, etc , Get all objects in the scene , Add axis . The renderings are as follows :
The introduction of the file :
three.js // threejs It's based on WebGL API Advanced based on API
dat.gui.js // dat.GUI Provide operation interface , Easy to debug
OrbitControls.js // Track controller , Used to control the rotation and translation of objects in the scene
Description of main components :
The camera : Decide what needs to be rendered on the screen
Renderers : Based on camera and scene , Call the underlying layer api Perform drawing work
object : They are the main rendered objects , Like a square 、 sphere , Axis
2, Sample source code :
<!DOCTYPE html>
<html>
<head>
<title> Use threejs Create geometry add axis material shadow animation </title>
<script type="text/javascript" src="libs/three.js"></script>
<script type="text/javascript" src="libs/dat.gui.js"></script>
<script type="text/javascript" src="libs/OrbitControls.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="dom"></div>
<script type="text/javascript">
var camera;
var renderer;
function init() {
// Create a scene , It will contain all our elements , Like an object , Cameras and lights .
var scene = new THREE.Scene();
// Create a camera , It defines where we are looking
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// Aim the camera at the center of the scene
camera.position.x = 10;
camera.position.y = 50;
camera.position.z = 90;
camera.lookAt(scene.position);
var orbit = new THREE.OrbitControls(camera);
// Create a renderer and set the size ,WebGLRenderer The computer graphics card will be used to render the scene
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(new THREE.Color(0xEEEEEE));
renderer.setSize(window.innerWidth, window.innerHeight);
// Setting up the renderer requires shadow effects
renderer.shadowMapEnabled = true;
// Display the coordinate axis on the screen
var axes = new THREE.AxisHelper(100);
scene.add(axes);
// Add planes to the scene
var plane = createPlaneGeometryBasicMaterial();
scene.add(plane);
// Add the cube to the scene
var cube = createBoxGeometryLambertMaterial();
scene.add(cube);
// Add a sphere to the scene
var sphere = createSphereGeometryLambertMaterial();
scene.add(sphere);
// Add light to shadows
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-40, 60, -10);
// Set the light source that produces shadows
spotLight.castShadow = true;
spotLight.shadowCameraVisible = true;
scene.add(spotLight);
// Add the output of the renderer to HTML Elements
document.getElementById("dom").appendChild(renderer.domElement);
// Use GUI Debug library
var controls = new function () {
// Set initial value
this.rotationSpeed = 0.02;
this.bouncingSpeed = 0.03;
this.numberOfObjects = scene.children.length;
// Randomly generate a cube
this.addCube = function () {
// Add the cube to the scene
scene.add(createBoxGeometryLambertMaterialRandom());
// Update the number of objects in the interface
this.numberOfObjects = scene.children.length;
};
// Remove objects from the scene , Remove the last object added to the scene
this.removeCube = function () {
// Get all objects in the scene
var allChildren = scene.children;
var lastObject = allChildren[allChildren.length - 1];
// Remove only THREE.Mesh object
if (lastObject instanceof THREE.Mesh && lastObject != plane && lastObject != cube && lastObject != sphere) {
scene.remove(lastObject);
// Update the number of objects in the interface
this.numberOfObjects = scene.children.length;
}
};
// Print all objects in the scene
this.outputObjects = function () {
console.log(scene.children);
}
};
var gui = new dat.GUI();
// Set the value range of two variables
gui.add(controls, 'rotationSpeed', 0, 0.5);
gui.add(controls, 'bouncingSpeed', 0, 0.5);
// Add event
gui.add(controls, 'addCube');
gui.add(controls, 'removeCube');
gui.add(controls, 'outputObjects');
// Listening variables
gui.add(controls, 'numberOfObjects').listen();
// Start animation
renderScene();
// Create a cube of random size and color
function createBoxGeometryLambertMaterialRandom() {
var cubeSize = Math.ceil((Math.random() * 3));
// Create a cube and set the size
var cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
// MeshLambertMaterial Set the material
var cubeMaterial = new THREE.MeshLambertMaterial({color: Math.random() * 0xffffff});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
// Set the object to cast shadows
cube.castShadow = true;
// Set the name of the cube
cube.name = "cube-" + scene.children.length;
// Set cube position
cube.position.x = -30 + Math.round((Math.random() * 60));
cube.position.y = Math.round((Math.random() * 5));
cube.position.z = -20 + Math.round((Math.random() * 20));
return cube;
}
// Create a MeshLambertMaterial Cube of material
function createBoxGeometryLambertMaterial() {
// Create a cube and set the size
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
// MeshLambertMaterial Set the material
var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
// Set the object to cast shadows
cube.castShadow = true;
// Set cube position
cube.position.x = -4;
cube.position.y = 3;
cube.position.z = 0;
return cube;
}
// Create a cube of base material
function createBoxGeometryBasicMaterial() {
// Create a cube and set the size
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
// MeshBasicMaterial( The base material will not react to the light source, and will only render with the specified color )
var cubeMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
wireframe: true
});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
// Set cube position
cube.position.x = -10;
cube.position.y = 3;
cube.position.z = 0;
return cube;
}
// Create a plane
function createPlaneGeometryBasicMaterial() {
// Create the ground plane and set the size
var planeGeometry = new THREE.PlaneGeometry(100, 70);
var planeMaterial = new THREE.MeshBasicMaterial({
color: 0xcccccc
});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
// Set accept shadows
plane.receiveShadow = true;
// Set the plane position and rotate
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 0;
plane.position.y = 0;
plane.position.z = 0;
return plane;
}
// Create a spherical geometry
function createSphereGeometryLambertMaterial() {
// Create a sphere
var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
// var sphereMaterial = new THREE.MeshBasicMaterial({
// color: 0x7777ff,
// wireframe: true
// });
var sphereMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
// Set the object to cast shadows
sphere.castShadow = true;
// Location range
sphere.position.x = 20;
sphere.position.y = 4;
sphere.position.z = 2;
return sphere;
}
// Animation rendering
var step = 0;
function renderScene() {
// Traverse all sub objects in the scene
scene.traverse(function (e) {
if (e instanceof THREE.Mesh && e != sphere && e != plane) {
// Rotate the cube around its axis
e.rotation.x += controls.rotationSpeed;
e.rotation.y += controls.rotationSpeed;
e.rotation.z += controls.rotationSpeed;
}
});
orbit.update();
// Rotate the cube around its axis
cube.rotation.x += controls.rotationSpeed;
cube.rotation.y += controls.rotationSpeed;
cube.rotation.z += controls.rotationSpeed;
// Bounce the ball up and down
step += controls.bouncingSpeed;
sphere.position.x = 20 + ( 10 * (Math.cos(step)));
sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));
// Use requestAnimationFrame Function to render
requestAnimationFrame(renderScene);
renderer.render(scene, camera);
}
// Rendered scenes
renderer.render(scene, camera);
}
window.onload = init;
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Listen for resizing events
window.addEventListener('resize', onResize, false);
</script>
</body>
</html>
If you need a complete code, please leave a message or contact me on wechat :1171053128
边栏推荐
- IronXL for . NET 2022.6
- Resolved (sqlalchemy+pandas.read_sql) attributeerror: 'engine' object has no attribute 'execution_ options‘
- 一文带你了解BI的前世今身与企业数字化转型的关系
- [software reverse - basic knowledge] analysis method, assembly instruction architecture
- 灵魂三问:什么是接口测试,接口测试怎么玩,接口自动化测试怎么玩?
- UI自動化測試從此告別手動下載瀏覽器驅動
- Special Edition: spreadjs v15.1 vs spreadjs v15.0
- Excuse me, my request is a condition update, but it is blocked in the buffer. In this case, can I only flush the cache every time?
- An elegant program for Euclid‘s algorithm
- [array]566 Reshape the matrix - simple
猜你喜欢
线程基础知识
[数组]566. 重塑矩阵-简单
Use Firefox browser to quickly pick up Web image materials
面试字节,过关斩将直接干到 3 面,结果找了个架构师来吊打我?
我就一写代码的,王总整天和我谈格局...
The architect started to write a HelloWorld
Wechat applet development process (with mind map)
error Couldn‘t find a package. JSON file in "your path“
NEW:Devart dotConnect ADO. NET
NEW:Devart dotConnect ADO.NET
随机推荐
Online sql to excel (xls/xlsx) tool
MindFusion. Virtual Keyboard for WPF
Multimedia query
在线SQL转Excel(xls/xlsx)工具
Nmap user manual learning records
What is test development? Why do so many companies hire test developers now?
Deflocculant aminoiodotide eye drops
Clickhouse synchronization MySQL (based on materialization engine)
请问一下我的请求是条件更新,但在buffer中就被拦截了,这种情况我只能每次去flush缓存么?
花了2晚,拿到了吴恩达@斯坦福大学的机器学习课程证书
EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
Soul 3: what is interface testing, how to play interface testing, and how to play interface automation testing?
北京程序员的真实一天!!!!!
程序员的视力怎么样? | 每日趣闻
UI automation test farewell to manual download of browser driver
UI自动化测试从此告别手动下载浏览器驱动
Is there a sudden failure on the line? How to make emergency diagnosis, troubleshooting and recovery
Redis source code analysis: redis cluster
Nmap使用手册学习记录
【软件逆向-分析工具】反汇编和反编译工具