当前位置:网站首页>Use threejs to create geometry, dynamically add geometry, delete geometry, and add coordinate axes
Use threejs to create geometry, dynamically add geometry, delete geometry, and add coordinate 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 , 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 and add axes </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 = createBoxGeometryBasicMaterial();
scene.add(cube);
// Add a sphere to the scene
var sphere = createSphereGeometryLambertMaterial();
scene.add(sphere);
// Add the output of the renderer to HTML Elements
document.getElementById("dom").appendChild(renderer.domElement);
// Use GUI Debug library
var controls = new function () {
this.numberOfObjects = scene.children.length;
// Randomly generate a cube
this.addCube = function () {
// Add the cube to the scene
scene.add(createBoxGeometryLambertMaterial());
// 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();
// 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 createBoxGeometryLambertMaterial() {
var cubeSize = Math.ceil((Math.random() * 3));
// Create a cube and set the size
var cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
// MeshBasicMaterial Set the material
var cubeMaterial = new THREE.MeshBasicMaterial({
color: Math.random() * 0xffffff,
wireframe: true // linear
});
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 cube of base material
function createBoxGeometryBasicMaterial() {
// Create a cube and set the size
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
var cubeMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
wireframe: true // linear
});
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 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 // linear
});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
// Location range
sphere.position.x = 20;
sphere.position.y = 4;
sphere.position.z = 2;
return sphere;
}
function renderScene() {
orbit.update();
// Use requestAnimationFrame Function to render
requestAnimationFrame(renderScene);
renderer.render(scene, camera);
}
// Rendered scenes
renderer.render(scene, camera);
}
window.onload = init;
// Modify the scene as the form changes
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Listen for form 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
边栏推荐
- Some enterprise interview questions of unity interview
- @The problem of cross database query invalidation caused by transactional annotation
- lds链接的 顺序问题
- BDF application - topology sequence
- IronXL for . NET 2022.6
- 请问一下我的请求是条件更新,但在buffer中就被拦截了,这种情况我只能每次去flush缓存么?
- “金九银十”是找工作的最佳时期吗?那倒未必
- [move pictures up, down, left and right through the keyboard in JS]
- 阿里云ECS使用cloudfs4oss挂载OSS
- Summary of scene design
猜你喜欢
JWT漏洞复现
Web components series (VII) -- life cycle of custom components
About the recent experience of writing questions
[brush questions] BFS topic selection
在线文本行固定长度填充工具
MindFusion.Virtual Keyboard for WPF
【web源码-代码审计方法】审计技巧及审计工具
Pyqt5 displays file names and pictures
3. Package the bottom navigation tabbar
grandMA2 onPC 3.1.2.5的DMX参数摸索
随机推荐
[wp][入门]刷弱类型题目
[web source code code code audit method] audit skills and tools
UI自动化测试从此告别手动下载浏览器驱动
[array]566 Reshape the matrix - simple
Containerd series - detailed explanation of plugins
我国算力规模排名全球第二:计算正向智算跨越
About the recent experience of writing questions
Web components series (VII) -- life cycle of custom components
NEW:Devart dotConnect ADO.NET
技术教程:如何利用EasyDSS将直播流推到七牛云?
The new project Galaxy token just announced by coinlist is gal
lds链接的 顺序问题
Phpmailer reported an error: SMTP error: failed to connect to server: (0)
Official announcement! The third cloud native programming challenge is officially launched!
This article takes you to understand the relationship between the past and present of Bi and the digital transformation of enterprises
汇编-入门
Quick start of UI component development of phantom engine [umg/slate]
[wp][introduction] brush weak type questions
一文带你了解BI的前世今身与企业数字化转型的关系
[understand series after reading] 6000 words teach you to realize interface automation from 0 to 1