I am facing difficulties in calculating bounding box points accurately when using three.js for rendering polygons in a 2D orthographic camera setup. The simple method of iterating over points to find extreme values does not function correctly after the camera has been rotated. It remains aligned with the axes, whereas I require the bounding box to be aligned with a viewport (similar to the illustration below). It should be rotatable at any angle while always staying aligned with the viewport.
I have provided an example below - how can I determine the bounding box points on the right side?
Image description: left - basic bounding box without rotation, middle - axis-aligned bounding box, right - desired output - viewport-aligned bounding box https://i.sstatic.net/xEzEA.png
Fiddle producing the middle case: https://jsfiddle.net/tqrc2ue6/5/
var camera, scene, renderer, geometry, material, line, axesHelper, boundingBoxGeometry, boundingBoxLine;
const polygonPoints = [{
x: 10,
y: 10,
z: 0
},
{
x: 15,
y: 15,
z: 0
},
{
x: 20,
y: 10,
z: 0
},
{
x: 25,
y: 20,
z: 0
},
{
x: 15,
y: 20,
z: 0
},
{
x: 10,
y: 10,
z: 0
},
]
function getBoundingBoxGeometry(geometry) {
geometry.computeBoundingBox();
const boundingBox = geometry.boundingBox;
const boundingBoxPoints = [{
x: boundingBox.min.x,
y: boundingBox.min.y,
z: 0
},
{
x: boundingBox.max.x,
y: boundingBox.min.y,
z: 0
},
{
x: boundingBox.max.x,
y: boundingBox.max.y,
z: 0
},
{
x: boundingBox.min.x,
y: boundingBox.max.y,
z: 0
},
{
x: boundingBox.min.x,
y: boundingBox.min.y,
z: 0
},
];
return new THREE.BufferGeometry().setFromPoints(boundingBoxPoints);
}
init();
animate();
function init() {
scene = new THREE.Scene();
axesHelper = new THREE.AxesHelper(10);
scene.add(axesHelper);
var frustumSize = 50
var aspect = window.innerWidth / window.innerHeight;
camera = new THREE.OrthographicCamera(frustumSize * aspect / -2, frustumSize * aspect / 2, frustumSize / 2, frustumSize / -2, -1, 1);
camera.rotation.z = 3 * Math.PI / 4
camera.position.set(15, 15)
scene.add(camera);
geometry = new THREE.BufferGeometry().setFromPoints(polygonPoints);
boundingBoxGeometry = getBoundingBoxGeometry(geometry);
material = new THREE.LineBasicMaterial({
color: 0xffffff
});
line = new THREE.Line(geometry, material);
scene.add(line);
boundingBoxLine = new THREE.Line(boundingBoxGeometry, material)
scene.add(boundingBoxLine);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}