How can you transform a threejs perspective camera into an orthographic one?

After converting a perspective camera to an orthographic camera, I noticed that the model appears very tiny and hard to see. I have already calculated the zoom factor for the orthographic camera based on the distance and FOV, but I'm unsure if there are any other properties that need to be adjusted (such as clipping plane settings).

I believe the position of the camera remains unchanged, but I am unsure if there are additional calculations or properties that I may have overlooked.

    fieldOfView = viewInfo.fov;
var getCameraPosition = function() {
    return viewer._viewport._implementation.getCamera()._nativeCamera.position;
};

// Calculate the delta position between the camera and the object
var getPositionDelta = function(position1, position2) {
    return {
        x: position1.x - position2.x,
        y: position1.y - position2.y,
        z: position1.z - position2.z
    }
};

var getDistance = function(positionDelta, cameraDirection) {
    return dot(positionDelta, cameraDirection);
};

distance = getDistance(positionDelta, cameraDirection),
var depth = distance;

var viewportWidth = view.getDomRef().getBoundingClientRect().width;
var viewportHeight = view.getDomRef().getBoundingClientRect().height;
var aspect = viewportWidth / viewportHeight;

var height_ortho = depth * 2 * Math.atan( fieldOfView * (Math.PI/180) / 2 )
var width_ortho  = height_ortho * aspect;

var near = viewInfo.near, far = viewInfo.far;
var newCamera = new THREE.OrthographicCamera(
    width_ortho  / -2, width_ortho   /  2,
    height_ortho /  2, height_ortho  / -2,
    near, far );


newCamera.position.copy( viewInfo.position );
var sCamera = new vk.threejs.OrthographicCamera(); //framework creatio of threejs cam

sCamera.setZoomFactor(orthoZoomFactor);
sCamera.setCameraRef(newCamera);
view.getViewport().setCamera(sCamera);

I experimented with setting the same camera properties (e.g. clipping planes) for the orthographic camera as in the perspective view, but encountered the same issue.

It seems like there might be a missing property or calculation needed to correctly position the object in the orthographic camera view compared to the original perspective view.

Answer №1

If we consider a scenario where you have a perspective view with a specific vertical field of view angle labeled as fov_y (measured in degrees) and you are aware of the viewport dimensions, width and height, along with the values of the near and far planes, these are essential for configuring the THREE.PerspectiveCamera:

perspCamera = new THREE.PerspectiveCamera( fov_y, width / height, near, far );

In addition, having knowledge of the object's position and the camera's position is crucial. While an object might have multiple positions, it's important to select a representative depth position.

The initial step involves computing the depth of the object:

var v3_object = .... // THREE.Vector3 : positon of the object
var v3_camera = perspCamera.position;

var line_of_sight = new THREE.Vector3();
perspCamera.getWorldDirection( line_of_sight );

var v3_distance = v3_object.clone().sub( v3_camera );
depth = v3_distance.dot( line_of_sight );

Subsequently, calculating the "size" of the rectangle projected onto the viewport at the calculated depth becomes necessary:

https://i.sstatic.net/9hnnN.png

aspect = width / height;

height_ortho = depth * 2 * Math.atan( fov_y*(Math.PI/180) / 2 )
width_ortho  = height_ortho * aspect;

With these computed values, setting up the THREE.OrthographicCamera can be performed using the following parameters:

var orthoCamera = new THREE.OrthographicCamera(
    width_ortho  / -2, width_ortho   /  2,
    height_ortho /  2, height_ortho  / -2,
    near, far );
orthoCamera.position.copy( perspCamera.position ); 



To transfer the position and direction from the perspective camera to the orthographic camera, follow this method:

orthoCamera.position.copy( perspCamera.position );
orthoCamera.quaternion.copy( perspCamera.quaternion ); 

For further insights, refer to the stackoverflow question titled Three.js - Find the current LookAt of a camera?

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

Ajax is working effectively as the first post is successful and the second post is able to retrieve data

UPDATE: I resolved the issue by relocating my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). By doing this, the functions are always re-loaded and attached to the "new" form each time the div is refreshed. ...

What is the best way to integrate AJAX with draggable columns in a Laravel application?

I have successfully integrated draggable functionality for table columns using jQuery Sortable within my Laravel application. I am now facing the challenge of updating the database with the data from these columns through AJAX. Despite researching online ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

What is the best way to define a constant in the main scope that relies on a function parameter?

I'm currently exploring next-auth and I'm interested in leveraging unstable_getserversession. According to the documentation, I need to import options from another file. import { authOptions } from 'pages/api/auth/[...nextauth]' Howeve ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...

WordPress display issue: AMCharts chart won't appear

I recently crafted an XY 2 series chart using the Amcharts library and have successfully integrated it into my WordPress website with the necessary plugin. This particular chart showcases load span values for construction spreader beams, and it was built ...

A guide to seamlessly adding calendar events with JSON data using the powerful Ionic Native Calendar Plugin

Hello there, I am in the process of developing an Ionic app and incorporating the Ionic Native Calendar plugin. My goal is to utilize this plugin to dynamically adjust the calendar event parameters through JSON linked to a Firebase database, rather than h ...

Chrome fails to select item in Protractor test, while Safari succeeds

While my test passes smoothly on Safari, I encountered an issue on Chrome where the following code snippet fails to work: it('should click the first source and get to the source preview page', function () { var grid_icon = element(by.css(&a ...

A method for increasing a counter using only an instance of a class or function without accessing its methods or properties in Javascript

Looking at the task ahead, let increment = new Increment(); I have been tasked with creating a Javascript class or function called Increment in order to achieve the following: console.log(`${increment}`) // should output 1 console.log(`${increment}`); ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

What is the best way to remove excess content that falls outside the viewBox?

Is there a function or method to trim a path that extends beyond the viewbox rather than simply concealing it? I am currently using svg-edit, which has a specific viewbox or canvas area. Any elements drawn outside of this canvas remain hidden. However, wh ...

Implement a function in JavaScript to sum quantities for identical JSON objects

I am looking to calculate the total quantity for each category. var items = [ { cat: 'EK-1',name:"test",info:"mat", quantity: 3}, { cat: 'EK-2', name:"test2",info:"na ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

The export button in the React Material Table doesn't seem to be displaying correctly

[I am encountering an issue with the React export button in Material Table. The bar is not showing completely. My code includes the following: options = {{exportButton:true}} How can I resolve this?]1 ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

Show the helper text when a TextField is selected in Material UI

I would like the error message to only show up when a user clicks on the TextField. Here's my code: import React, { useState, useEffect } from 'react'; import { TextField, Grid, Button } from '@material-ui/core'; const ReplyToComm ...

implementing data in a single component using vue.js

I am facing an issue with a component where I need to fetch data using an ajax call. The component is being called correctly and the data is returned in the ajax call, but I am struggling to assign it to the data in the template? <template> < ...

Dynamic HTML5 elements in constant motion

I'm interested in creating an HTML5 canvas that features bouncing circle and square elements that interact with each other, potentially spinning upon collision. The best example I've come across so far is located at this link. var canvas = docu ...

Using JSON to pass a function with parameters

I have a small issue that I'm struggling to solve. My dilemma lies in sending a JSON with a function, along with parameters. Typically, it's easy to send a function in JSON like this: var jsonVariable = { var1 : 'value1', var2 : &apos ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...