Checking if a Vector3 is visible within a camera's field of view using three.js

Is there a simple and cost-effective way to determine if a point or Vector3 is within the field of view of a camera using three.js?

I would like to create a grid of boxes to cover the "floor" of a scene, but only up to the edges of the visible area, without being affected by panning or rotation. It would also be beneficial to restrict the depth at which the boxes can exist from the camera's position.

Although I haven't been able to find a definitive answer yet, I suspect it might be because I'm not using the correct terminology. Any clarification and a quick example would be greatly appreciated.

Here is a starting code snippet:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var vec = new THREE.Vector3(0, 0, 10);
          
//??? How do I determine if the Vector3 is within the camera's view?

var renderer = new THREE.WebGLRenderer();
document.body.appendChild( renderer.domElement );

console.log('Currently, the screen is just blank.');}
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
<head>
<meta charset=utf-8>
<title>Spot the Vector</title>
</head>
<body>
<script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
</body>
</html>

Answer №1

Refer to the camera frustrum setup outlined in this solution

Afterwards, execute the following code:

if(frustum.containsPoint( vec ))  
    { ...

UPDATE: Here is a comprehensive example tailored to the question above:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

//var vec = new THREE.Vector3(0, 0, 10); //behind camera
var vec = new THREE.Vector3(0, 0, -10); //in front of camera

//check if within camera's view:
camera.updateMatrix(); // make sure camera's local matrix is updated
camera.updateMatrixWorld(); // make sure camera's world matrix is updated
camera.matrixWorldInverse.getInverse( camera.matrixWorld );

var frustum = new THREE.Frustum();
frustum.setFromMatrix( new THREE.Matrix4().multiply( camera.projectionMatrix, camera.matrixWorldInverse ) );

if(frustum.containsPoint(vec)) {
  console.log('within camera view');
} else {
  console.log('outside camera view');
}

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
  <head>
    <meta charset=utf-8>
    <title>Spot the Vector</title>
  </head>
  <body>
    <script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
  </body>
</html>

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

Adding Node.js Express responses to a running list

I have a situation in one route where I am using multiple instances of res.send. Is there a way to combine them all into one and then send the aggregated list at the end? The format I prefer is as follows: { "writer": {success message}, "archive": {succes ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

What is the best way to retrieve the initial <ul> element from a JavaScript document?

Just to clarify, I'm looking to target a specific div with a class and the first <ul> from a document (specifically in blogger). Currently, I have a JavaScript function that grabs the first image and generates a thumbnail as shown below: //< ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created. Check out the co ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

The Electron application is experiencing difficulties locating the module at /resources/app/index.js

Just started my journey with electron and successfully created my first electron application. It runs perfectly fine with npm start, but I encounter issues when trying to execute it with npm run. (I am using Ubuntu Linux). The command line interface displa ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Multimaterial Intersection with Ray Casting

Why does raycast intersection fail when using multisurface materials like LambertMaterial with wireframe:true combined with LambertMaterial in just color on a mesh? When I apply a "solid" material (any material without wireframe:true), the intersection w ...

Tips for Utilizing CSS Overflow: Hidden to Prevent the Parent Container from Expanding

I have a fixed width column and a fluid column. In the fluid column, I want to display a string with nowrap so that it does not overflow the container. Here is an illustration of how I want the text to appear: --------------------------------------------- ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Activate the Jquery-ui Tooltip with a click event

Here is the code I'm using: function DrawTipsProgress(postid, ajaxurl) { var data = { action: 'ajax_action', post_id: postid } jQuery('#dashicon-' + postid).on("click", function () { jQuery.p ...

Achieving a 3D textured effect in WebGL/three.js by utilizing a workaround for 2D textures

Wanting to incorporate 3D textures for my WebGL-rendered objects, I am currently employing a specific method in the fragment shader. This approach was recommended on WebGL and OpenGL Differences: // tex represents a texture with each cube slice positioned ...

Utilizing the useEffect hook with outdated information

As I was learning about react hooks, I encountered a perplexing issue that I can't quite grasp. My goal is to create a list of numbers that can be incremented and should always display in descending order. However, when I input a high number initially ...

Error: The symbol $ is not recognized

This is a snippet of code that I've written to automate address filling and extract latitude/longitude/address information. <html> <head> <LINK rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" sr ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

Using Node.js Express to showcase a JSON file utilizing Class Methods

Recently diving into node.js and express, I attempted to display a JSON file containing an array of 3 objects using a class method Below is the Class structure: const fs = require('fs') class GrupoArchivo { constructor(filePath) { t ...

Different boolean variable assigned to every item in v-for loop

I am working on creating a custom play/pause button for my audio elements, and here is how I have implemented it: <div v-for="(post, p) in post_list"> <!-- ... --> <!-- ... --> <!-- ... --> <v-avatar v-i ...