Is there a way to use code to target a mesh in a three.js scene when a button is clicked?

When a button is clicked, I want a Three.js Mesh to be focused based on the button. For example, when the "view top" button is clicked, the mesh should be focused from the top.
Is there an inbuilt method in three.js to focus a mesh or how can I calculate the top left front of a mesh?

var scene, camera, renderer, controls;
var ROTATE = true;

function init() {
    // Initialization code for Three.js scene, camera, controls, and lights
}

function topView(){
  alert("topView view") 
}

function sideView(){
  alert("sideview view") 
}

function frontView(){
  alert("front view") 
}
* {
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
}

body {
  background: #000;
  font: 30px sans-serif;
}
button{
  padding:5px 10px
}
<button onClick={topView()}>top view</button>
<button onClick={frontView()}>front view</button>
<button onClick={sideView()}>side view</button>

The above code is a demo. Trying to update the camera position forcefully does not work.

Answer №1

To obtain an axis-aligned bounding box, you can use the new THREE.Box3().setFromObject(mesh) method, and then adjust the camera to fit this box accordingly. Below is a TypeScript code snippet that achieves this, functioning well with PerspetiveCamera and OrbitControls.

adjustCameraToBoundingBox(boundingBox: THREE.Box3) {
    const camera = this._camera;
    const objectPosition = boundingBox.getCenter(new THREE.Vector3());
    const objectSize = boundingBox.getSize(new THREE.Vector3());
    boundingBox.min.y = 0;
    boundingBox.max.y = 0;
    const boundingSphere = boundingBox.getBoundingSphere(new THREE.Sphere());

    let dimension = boundingSphere.radius * 2;
    if (dimension < camera.near) {
        dimension = camera.near;
    }

    const viewDirection = THREE.Object3D.DefaultUp.clone();

    const fieldOfView = THREE.Math.degToRad(camera.fov);

    let dist = dimension / (2.0 * Math.tan(fieldOfView / 2.0));

    if (camera.aspect <= 1) {
        dist = dist / camera.aspect;            
    }

    if (dist < camera.near) {
        dist = objectSize.y;
    }

    if (dist < camera.near) {
        dist = camera.near;
    }

    camera.position.copy(objectPosition.clone().add(viewDirection.multiplyScalar(dist)));

    if (this._orbitControls) {
        this._orbitControls.target.copy(objectPosition); 
        this._orbitControls.rotateLeft(Math.PI);                        
    } else {
        camera.lookAt(objectPosition);
    }

    camera.updateProjectionMatrix();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

Hide jquery scroll bar

I am currently working on a WordPress plugin with the Twenty Thirteen theme. My goal is to display a modal when a div is clicked, and at that time I want to hide the scrollbar on the body of the page. Despite trying the following code snippet, it doesn&ap ...

Binding Events to Elements within an AngularJS-powered User Interface using a LoopIterator

I am working with an Array of Objects in AngularJS that includes: EmployeeComments ManagerComments ParticipantsComments. [{ "id": "1", "title": "Question1", "ManagerComment": "This was a Job Wel Done", "EmployeeComment": "Wow I am Surprised", ...

What is the best way to integrate PHP code into my countdown JavaScript code to automatically insert data into a MySQL column once the countdown has reached

I have created a countdown JavaScript code that resets every day at 23:00 of local time. I am wondering if it is possible to incorporate PHP code into this script so that after the countdown finishes each day, it automatically adds "5" to my "Credit" col ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Strategies for Structuring Django and JavaScript Codebases

I'm grappling with the best way to structure my javascript and django code. Previously, I would include my page-specific javascript directly in the template file within a <script> tag. However, as my javascript code grew, this approach led to a ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Leveraging jQuery to execute a post request and showcase the subsequent page seamlessly

I have set up a booking engine that utilizes a POST method. I incorporated the XDate library which is functioning perfectly. However, I am facing an issue where the booking engine is not displaying the new page from the booking engine website after executi ...

Error encountered: SyntaxError - Missing semicolon before statement in AJAX call while processing JSON data

I am currently in the process of making a cross domain JSONP call utilizing this code snippet: jQuery.ajax({ async: true, url: 'http://mnews.hostoi.com/test.json', dataType: 'jsonp', method: "GET&quo ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

What is the best way to show search results in real-time as a user

While working on a search box feature that filters and displays results as the user types, I encountered an issue where the search results keep toggling between showing and hiding with each letter input. As a beginner in JS, I am hoping for a simple soluti ...

How to insert an image into a placeholder in an .hbs Ember template file

I'm looking to enhance a .hbs template file in ember by incorporating an image. I am not a developer, but I'm attempting to customize the basic todo list app. <section class='todoapp'> <header id='header'> & ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...

Tips for invoking the setState method via an onClick event the ES6 way

class BlogPost extends React.Component{ //getInitialState constructor(){ super(); this.onLike = this.onLike.bind(this); this.state = { like :0 } } onLike(){ this.setState({ li ...

Utilizing JavaScript to create a single selection from two Listboxes

Seeking assistance with integrating ASP.NET (C#) code. In my web application, I have implemented two listboxes - one displaying a list of companies fetched from the database (lstCompanies), and the other allows users to filter these companies (lstFilter). ...

Combining Laravel and VueJs for a Multi-Page Application (MPA)

I have recently developed a website using a combination of Laravel and VueJs. However, I am facing some confusion regarding the most suitable routing architecture to implement. Currently, my application has the following setup: The routing system is man ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...