使用three.js;
代码;
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>第一个three.js 示例</title><style>body {margin: 0;overflow: hidden;}</style><script src="./build/three.js"></script>
</head><body><script>var scene = new THREE.Scene();var geometry = new THREE.SphereGeometry(120, 60, 60); //创建一个球体几何对象var material = new THREE.MeshLambertMaterial({color: 0x0000ff}); //材质var mesh = new THREE.Mesh(geometry, material); //网格模型对象var mesh2 = new THREE.Mesh(geometry, null);scene.add(mesh); //网格模型添加到场景中//点光源var point = new THREE.PointLight(0xffffff);point.position.set(400, 200, 300); //点光源位置scene.add(point); //点光源添加到场景中/*** 相机*/var width = window.innerWidth; //窗口宽度var height = window.innerHeight; //窗口高度var k = width / height; //窗口宽高比var s = 200; //三维场景显示范围控制系数//创建相机var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);camera.position.set(200, 300, 200); //相机位置camera.lookAt(scene.position); //相机方向/*** 渲染器*/var renderer = new THREE.WebGLRenderer();renderer.setSize(width*1/4, height*1/4);//设置渲染区域尺寸renderer.setClearColor(0xffff00, 1); //设置背景颜色document.body.appendChild(renderer.domElement); //body元素中插入canvas对象//执行渲染操作 指定场景、相机作为参数renderer.render(scene, camera);// 包围盒计算模型对象的大小和位置const box3 = new THREE.Box3();box3.expandByObject(mesh); // 计算模型包围盒const size = new THREE.Vector3();box3.getSize(size); // 计算包围盒尺寸// console.log('模型包围盒尺寸',size);alert('box size is: '+ size.x+","+size.y+","+size.z);const center = new THREE.Vector3();box3.getCenter(center); // 计算包围盒中心坐标// console.log('模型中心坐标',center);alert('center: '+ center.x+","+center.y+","+center.z);box3.expandByObject(mesh2); // 计算模型包围盒const size2 = new THREE.Vector3();box3.getSize(size2); // 计算包围盒尺寸alert('box size is: '+ size2.x+","+size2.y+","+size2.z);</script>
</body>
</html>
根据three.js手册;
Box3
在3D空间中表示一个盒子或立方体。这个的主要目的是表示对象的最小边界框Minimum Bounding Boxes;
运行如下;
SphereGeometry的第一个参数是半径,这就对了,直径是240;一个长宽高都是240的立方体就可以包围此球体;
但是SphereGeometry的后2个参数不是球的x和y坐标;根据手册,是,
widthSegments — 水平分段数(沿着经线分段),最小值为3,默认值为8;
heightSegments — 垂直分段数(沿着纬线分段),最小值为2,默认值为6;
看上去比较费解,下回继续;