JSFiddle - React, Tailwind, and code Playground
by neeh
HTML
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
CSS
body {
background: #202020;
margin: 0;
overflow: hidden;
}
JavaScript
var scene, camera, renderer;
var controls;
var COLORS = [0xffffff, 0xd40000, 0x0084ff];
function buildGroup(count) {
var group = new THREE.Group();
for (var i = 0; i < count; i++) {
var color = COLORS[Math.floor(Math.random() * COLORS.length)];
var mesh = new THREE.Mesh(
new THREE.SphereBufferGeometry(Math.random() * 0.5 + 0.5, 36, 24),
new THREE.MeshPhongMaterial({ color: color })
);
mesh.position.set(Math.random() * 10.0, Math.random() * 10.0, Math.random() * 10.0);
group.add(mesh);
}
return group;
}
/**
* Compute the center of a THREE.Group by creating a bounding box
* containing every children's bounding box.
* @param {THREE.Group} group - the input group
* @param {THREE.Vector3=} optionalTarget - an optional output point
* @return {THREE.Vector3} the center of the group
*/
var computeGroupCenter = (function () {
var childBox = new THREE.Box3();
var groupBox = new THREE.Box3();
var invMatrixWorld = new THREE.Matrix4();
return function (group, optionalTarget) {
if (!optionalTarget) optionalTarget = new THREE.Vector3();
group.traverse(function (child) {
if (child instanceof THREE.Mesh) {
if (!child.geometry.boundingBox) {
child.geometry.computeBoundingBox();
childBox.copy(child.geometry.boundingBox);
child.updateMatrixWorld(true);
childBox.applyMatrix4(child.matrixWorld);
groupBox.min.min(childBox.min);
groupBox.max.max(childBox.max);
}
}
});
// All computations are in world space
// But the group might not be in world space
group.matrixWorld.getInverse(invMatrixWorld);
groupBox.applyMatrix4(invMatrixWorld);
groupBox.getCenter(optionalTarget);
return optionalTarget;
...