Three.js MapControls 地图控件绘制随机柱形

204 阅读3分钟

chrome-capture-2024-9-24.gif

官网示例地址:www.douchuanwei.com/api/ar/thre…

一、认识MapControls

1. 什么是 MapControls

MapControls是three.js 的一个拓展库,用于控制摄像机在地图或三维场景中移动、旋转和缩放的控制器。它允许用户通过鼠标或触摸操作来与三维场景进行交互,类似于在地图应用中导航和缩放视图。

本质上:就是改变相机的参数,比如相机的位置属性、相机目标观察点。

controls.addEventListener('change', function () {
    // 鼠标右键旋转时候,查看.position变化
    // 鼠标左键拖动的时候,查看.position、.target的位置会变化
    console.log('camera.position',camera.position);
    console.log('controls.target',controls.target);
});

2.使用方法

import * as THREE from 'three';  
import { MapControls } from 'three/examples/jsm/controls/MapControls.js';  
  
// 创建场景、摄像机和渲染器(这里省略了部分代码)  
  
// 创建MapControls实例  
const controls = new MapControls(camera, renderer.domElement);  
  
// 动画循环  
function animate() {  
    requestAnimationFrame(animate);  
  
    // 更新MapControls状态  
    controls.update();  
  
    // 渲染场景  
    renderer.render(scene, camera);  
}  
  
// 启动动画循环  
animate();

3. 对比 MapControls 和 OrbitControls

MapControls:专为地图或具有大范围导航需求的三维场景设计。它允许用户通过鼠标或触摸操作来平移、旋转和缩放摄像机,以便更好地浏览和导航大型场景。

OrbitControls:则是一个更通用的摄像机控制器,用于控制摄像机围绕目标物体进行旋转、缩放和平移操作。它模拟了地球围绕太阳运动的轨道行为,使得用户可以从不同角度观察三维场景中的物体。

二、示例解读

1. 实现步骤

  • 初始化场景、渲染器
  • 实例化 MapControls 地图导航相机控件
  • 生成500个随机大小和位置的立方缓冲体, 放置在场景中

三、 示例代码

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgl - map controls</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: #ccc;
				color: #000;
			}

			a {
				color: #f00;
			}
		</style>
	</head>

	<body>
		<div id="info">
			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - map controls
		</div>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.module.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';

			import { MapControls } from 'three/addons/controls/MapControls.js';

			let camera, controls, scene, renderer;

			init();
			//render(); // remove when using next line for animation loop (requestAnimationFrame)
			animate();

			function init() {

				scene = new THREE.Scene();
				scene.background = new THREE.Color( 0xcccccc );
				// 定义雾
				scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );

				renderer = new THREE.WebGLRenderer( { antialias: true } );
				// 设置设备像素比。通常用于避免 HiDPI 设备上绘图模糊
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				document.body.appendChild( renderer.domElement );

				camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
				camera.position.set( 0, 200, - 400 );

				// controls

				controls = new MapControls( camera, renderer.domElement );

				//controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

				controls.enableDamping = true; // 启用阻尼或自动旋转时,需要动画循环
				controls.dampingFactor = 0.05; // 设置阻尼惯性多大,默认是 0.05  注意:这一值生效,必须在动画循环里调用 .update()

				/**
				 * screenSpacePanning:
				 * 定义当平移的时候摄像机的位置将如何移动。
				 * true: 摄像机再屏幕空间内平移
				 * fasle: 将在和摄像机向上方向垂直的平面中平移
				 * 当使用 OrbitControls 时候, 默认为true
				 * 当使用MapControls时候,默认为false
				*/
				controls.screenSpacePanning = false;

				controls.minDistance = 100; // 能够将相机向内移动多少,默认值为0
				controls.maxDistance = 500; // 能够将相机向外移动多少,默认值是 Infinity

				// 你能够垂直旋转的角度的上限,范围是0到Math.PI,其默认值为Math.PI。
				controls.maxPolarAngle = Math.PI / 2;


				// world
				// 生成500个随机大小和位置的立方缓冲体
				const geometry = new THREE.BoxGeometry();
				geometry.translate( 0, 0.5, 0 );
				const material = new THREE.MeshPhongMaterial( { color: 0xeeeeee, flatShading: true } );

				for ( let i = 0; i < 500; i ++ ) {

					const mesh = new THREE.Mesh( geometry, material );
					mesh.position.x = Math.random() * 1600 - 800;
					mesh.position.y = 0;
					mesh.position.z = Math.random() * 1600 - 800;
					mesh.scale.x = 20;
					mesh.scale.y = Math.random() * 80 + 10;
					mesh.scale.z = 20;
					mesh.updateMatrix(); // 更新局部变换
					// 当这个属性设置了之后,它将计算每一帧的位移、旋转(四元变换)和缩放矩阵,并重新计算matrixWorld属性。默认值是Object3D.DEFAULT_MATRIX_AUTO_UPDATE (true)。
					mesh.matrixAutoUpdate = false;
					scene.add( mesh );

				}

				// lights

				const dirLight1 = new THREE.DirectionalLight( 0xffffff, 3 );
				dirLight1.position.set( 1, 1, 1 );
				scene.add( dirLight1 );

				const dirLight2 = new THREE.DirectionalLight( 0x002288, 3 );
				dirLight2.position.set( - 1, - 1, - 1 );
				scene.add( dirLight2 );
				// AmbientLight: 自然光
				const ambientLight = new THREE.AmbientLight( 0x555555 );
				scene.add( ambientLight );

				//

				window.addEventListener( 'resize', onWindowResize );


				const gui = new GUI();
        // Setting this property to true allows to zoom to the cursor's position. Default is false.
				gui.add( controls, 'zoomToCursor' );
				gui.add( controls, 'screenSpacePanning' );

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {

				requestAnimationFrame( animate );

				controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true

				render();

			}

			function render() {

				renderer.render( scene, camera );

			}

		</script>

	</body>
</html>