我们在项目中会有一些这样的需求,我们可视化一个场景,需要俯视、平移、缩放,方便观察场景中的数据或者模型,之所以把这个案例拿出来
1、这是个很实用的需求,我相信很多人会用到
2、我自己认为在实际案例中我们可以学习相关知识点更易吸收些
为了丰富本篇文章知识点,我还加入了一个物体沿轨迹运动的场景,下面代码会介绍到,回到之前的问题three中可以利用对 OrbitControls 的设置很轻松的实现相关场景,代码如下:
controls = new OrbitControls( camera, renderer.domElement );// 移动端控制平移 缩放// controls.touches = {// ONE: THREE.TOUCH.PAN,// TWO: THREE.TOUCH.DOLLY_PAN// };// PC 左平移,右旋转 滚轮放大缩小 默认是右平移controls.mouseButtons = {LEFT: THREE.MOUSE.PAN,MIDDLE: THREE.MOUSE.DOLLY,RIGHT: THREE.MOUSE.ROTATE};// 设置最大最小视距controls.minDistance = 20;controls.maxDistance = 1000;controls.autoRotate = false;controls.enableRotate = false;controls.enablePan = true;
需要注意的是移动端和PC是不同的配置,minDistance和maxDistance按实际需求设置即可,到这一步只是对controls的操作,已经有能力实现效果了,但是camera的设置也是不可或缺的,即camera必须是俯视的
先上下整体效果图
看下代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><style>body {width: 100%;height: 100%;}* {margin: 0;padding: 0;}.label {font-size: 20px;color: #000;font-weight: 700;}</style>
</head>
<body>
<div id="container"></div>
<script type="importmap">{"imports": {"three": "../three-155/build/three.module.js","three/addons/": "../three-155/examples/jsm/"}}
</script>
<script type="module">
import * as THREE from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
let stats, labelRenderer, curve, movingObjects;
let camera, scene, renderer, mesBox, target, controls;
const group = new THREE.Group();
let progress = 0; // 物体运动时在运动路径的初始位置,范围0~1
const velocity = 0.0005; // 影响运动速率的一个值,范围0~1,需要和渲染频率结合计算才能得到真正的速率
let widthImg = 200;
let heightImg = 200;
init();
initHelp();
initLight();
axesHelperWord();
animate();
// 添加一个物体
mesBox = addGeometries();
// 添加平面
addPlane();
// 添加路径
makeCurve();
// 添加一个运动的物体
movingObjects = addMovingObjects();window.addEventListener('mousemove', mousemoveFun);function addPlane() {// 创建一个平面 PlaneGeometry(width, height, widthSegments, heightSegments)const planeGeometry = new THREE.PlaneGeometry(widthImg, heightImg, 1, 1);// 创建 Lambert 材质:会对场景中的光源作出反应,但表现为暗淡,而不光亮。const planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});const plane = new THREE.Mesh(planeGeometry, planeMaterial);// 以自身中心为旋转轴,绕 x 轴顺时针旋转 45 度plane.rotation.x = -0.5 * Math.PI;plane.position.set(0, -4, 0);scene.add(plane);
}function addGeometries() {let img = new THREE.TextureLoader().load('../materials/img/view4.jpg');img.repeat.x = img.repeat.y = 5;const geometry = new THREE.BoxGeometry( 10, 10, 10 );let material = new THREE.MeshPhongMaterial({map: img,flatShading: true,side: THREE.DoubleSide,transparent: 1});const mesh = new THREE.Mesh( geometry, material );mesh.position.x = 0;mesh.position.y = 0;mesh.position.z = -20;scene.add( mesh );return mesh;
}function addMovingObjects() {let img = new THREE.TextureLoader().load('../materials/img/view3.jpg');const geometry = new THREE.BoxGeometry( 10, 10, 10 );const material = new THREE.MeshPhongMaterial({map: img,flatShading: true,side: THREE.DoubleSide,transparent: 1});const mesh = new THREE.Mesh( geometry, material );scene.add( mesh );return mesh;
}function makeCurve() {// 创建一个环形路径curve = new THREE.CatmullRomCurve3([new THREE.Vector3(80, 0, 80),new THREE.Vector3(80, 0, -80),new THREE.Vector3(-80, 0, -80),new THREE.Vector3(-80, 0, 80)]);curve.curveType = "catmullrom";curve.closed = true;//设置是否闭环curve.tension = 0; //设置线的张力,0为无弧度折线// 为曲线添加材质在场景中显示出来,不显示也不会影响运动轨迹,相当于一个Helperconst points = curve.getPoints(20);const geometry = new THREE.BufferGeometry().setFromPoints(points);const material = new THREE.LineBasicMaterial({color: '#f00',linewidth: 1});// Create the final object to add to the sceneconst curveObject = new THREE.Line(geometry, material);curveObject.position.y = 1;curveObject.visible = false;scene.add(curveObject);
}function mousemoveFun() {let width = widthImg;let height = heightImg;let newPo;let newPoHeight;const prevPos = camera.position.clone();if (camera.position['x'] > width / 2) {newPo = width / 2 - 0.01;camera.position.set(newPo, prevPos.y, prevPos.z);controls.target = new THREE.Vector3(newPo, 0, prevPos.z);controls.enablePan = false;} else if (camera.position['x'] < -width / 2) {newPo = -width / 2 + 0.01;camera.position.set(newPo, prevPos.y, prevPos.z);controls.target = new THREE.Vector3(newPo, 0, prevPos.z);controls.enablePan = false;} else if (camera.position['z'] > height / 2) {// 因为我们的坐标系 y轴在上 所以平移时 height 即是 znewPoHeight = height / 2 - 0.01;camera.position.set(prevPos.x, prevPos.y, newPoHeight);controls.target = new THREE.Vector3(prevPos.x, 0, newPoHeight);controls.enablePan = false;} else if (camera.position['z'] < -height / 2) {newPoHeight = -height / 2 + 0.01;camera.position.set(prevPos.x, prevPos.y, newPoHeight);controls.target = new THREE.Vector3(prevPos.x, 0, newPoHeight);controls.enablePan = false;} else {controls.enablePan = true;}
}function init() {camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 10, 2000 );camera.up.set(0, 1, 0);camera.position.set(0, 100, 0);camera.lookAt(0, 0, 0);scene = new THREE.Scene();// scene.background = new THREE.Color( '#ccc' );renderer = new THREE.WebGLRenderer( { antialias: true } );renderer.setPixelRatio( window.devicePixelRatio );renderer.setSize( window.innerWidth, window.innerHeight );document.body.appendChild( renderer.domElement );labelRenderer = new CSS2DRenderer();labelRenderer.setSize( window.innerWidth, window.innerHeight );labelRenderer.domElement.style.position = 'absolute';labelRenderer.domElement.style.top = '0px';labelRenderer.domElement.style.pointerEvents = 'none';document.getElementById( 'container' ).appendChild( labelRenderer.domElement );controls = new OrbitControls( camera, renderer.domElement );// 移动端控制平移 缩放// controls.touches = {// ONE: THREE.TOUCH.PAN,// TWO: THREE.TOUCH.DOLLY_PAN// };// PC 左平移,右旋转 滚轮放大缩小 默认是右平移controls.mouseButtons = {LEFT: THREE.MOUSE.PAN,MIDDLE: THREE.MOUSE.DOLLY,RIGHT: THREE.MOUSE.ROTATE};// 设置最大最小视距controls.minDistance = 20;controls.maxDistance = 1000;controls.autoRotate = false;controls.enableRotate = false;controls.enablePan = true;window.addEventListener( 'resize', onWindowResize );stats = new Stats();stats.setMode(1); // 0: fps, 1: msdocument.body.appendChild( stats.dom );scene.add( group );
}function initLight() {let spotLight;spotLight = new THREE.SpotLight( 0xffffff, 500 );spotLight.name = 'Spot Light';spotLight.angle = Math.PI / 5;spotLight.penumbra = 0.1;spotLight.position.set( 0, 5, 10 );spotLight.castShadow = true;spotLight.shadow.camera.near = 2;spotLight.shadow.camera.far = 100;spotLight.shadow.mapSize.width = 1024;spotLight.shadow.mapSize.height = 1024;scene.add( spotLight );const AmbientLight = new THREE.AmbientLight(0xCCCCCC, 2);scene.add( AmbientLight );
}function initHelp() {// const size = 100;// const divisions = 5;// const gridHelper = new THREE.GridHelper( size, divisions );// scene.add( gridHelper );// The X axis is red. The Y axis is green. The Z axis is blue.const axesHelper = new THREE.AxesHelper( 100 );scene.add( axesHelper );
}function axesHelperWord() {let xP = addWord('X轴');let yP = addWord('Y轴');let zP = addWord('Z轴');xP.position.set(50, 0, 0);yP.position.set(0, 50, 0);zP.position.set(0, 0, 50);
}function addWord(word) {let name = `<span>${word}</span>`;let moonDiv = document.createElement( 'div' );moonDiv.className = 'label';// moonDiv.textContent = 'Moon';// moonDiv.style.marginTop = '-1em';moonDiv.innerHTML = name;const label = new CSS2DObject( moonDiv );group.add( label );return label;
}function onWindowResize() {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize( window.innerWidth, window.innerHeight );
}function animate() {requestAnimationFrame( animate );// mesh绕自身中心的 y 轴自转if (mesBox) {mesBox.rotation.y += 0.01;}if (curve && movingObjects) {if (progress <= 1 - velocity) {// 获取样条曲线指定点坐标const point = curve.getPointAt(progress);movingObjects.position.set(point.x, point.y, point.z);progress += velocity;} else {progress = 0;}}stats.update();controls.update();labelRenderer.render( scene, camera );renderer.render( scene, camera );
}
</script>
</body>
</html>
这里是全部代码,可以看出 three用的是 155版本,大家从官网上下载到本地改下路径即可。图片url你可以换成本地图片,项目就能跑起来了。
中间立方体在做了一个环绕自身y轴旋转,外面的立方体通过获取curve上的坐标点,沿着curve的轨迹运动。
这里有一些新的知识点:
new THREE.TextureLoader().load(‘…/materials/img/view3.jpg’);
TextureLoader是three加载图片的方法,我们还可以这样用
let loader = new THREE.TextureLoader();
loader.load(‘url’, (img) => {
// img 这个img就是加载完成后的图片
});
这时就一个疑问了,同步还是异步,我们来看源码
其实还是异步,拿到图片后我们发现material有一个map参数,可以接收图片作为材质,这样material就可以做的很丰富了,side是指物体的正反两面,THREE.DoubleSide即两面都要渲染,如果我们只看外面,不要设置这里,这样也能节省一些性能
let material = new THREE.MeshPhongMaterial({map: img,flatShading: true,side: THREE.DoubleSide,transparent: 1});
最后一个知识点,即物体沿着轨迹运动,我们把这一行代码
curveObject.visible = false; 改为 true 大家就可以看到这个轨迹了。
逻辑代码中已经写的很详细了,大家也可以思考下还有哪些方法可以作为curve使用。
如果感觉有用,点个赞不过分吧!!!