Creating a plane in Three.js using points along different axes

My goal is to construct a plane that intersects the points (2, 3, 12) on the x, y, and z axes respectively (equivalently, the equation of the plane is 6x + 4y + z = 12).

So far, I have attempted to generate a flat plane and rotate it around the three axes using the dot product technique. However, this method has only gotten me close to the desired plane, never quite reaching perfection.

I have a hunch that incorporating Matrix4 into my approach could lead to a more accurate result, but I haven't been able to locate a fitting example to guide me.

Answer №1

Let's discuss a method for constructing a plane. Using the example provided, you have three vectors that are multiples of the canonical basis i, j, k, represented as:

x = x_0 * [1 0 0]
y = y_0 * [0 1 0]
z = z_0 * [0 0 1]

A plane requires two important components:

  • a normal vector (perpendicular to the plane)
  • a distance from the origin to the plane

The normal vector can be obtained using the cross product of two non-parallel vectors lying on the plane, such as y - x and z - x. This gives us:

normal = normalize(cross(y - x, z - x))

When rendering the plane, an initial normal vector N is present. We can create a quaternion that rotates vector N to normal, using the axis-angle form:

q_{axis} = cross(N, normal)
q_{angle} = acos(dot(N, normal))

The distance to the plane can be determined using the dot product of the normal vector and any point on the plane, for example:

distance = dot(normal, x)

Notably, this distance value is signed, allowing easy movement of the plane in the normal direction by a distance of distance units.

Implementation

var plane = new THREE.Mesh(
  new THREE.PlaneGeometry(10, 10),
  new new THREE.MeshNormalMaterial()
)
// ...
function rotatePlane(x, y, z) {
  var xy = new THREE.Vector3().subVectors(y, x)
  var xz = new THREE.Vector3().subVectors(z, x)
  var normal = new THREE.Vector3().crossVectors(xy, xz).normalize()

  // initial normal vector of the plane
  var Z = new THREE.Vector3(0, 0, 1)
  var axis = new THREE.Vector3().crossVectors(Z, normal).normalize()
  var angle = Math.acos(Z.dot(normal))
  var q = new THREE.Quaternion().setFromAxisAngle(axis, angle)
  plane.rotation.setFromQuaternion(q)

  var distanceToPlane = x.dot(normal)
  plane.position.copy(normal.clone().multiplyScalar(distanceToPlane))
}

Demo

Update 1: To simplify the quaternion calculation, you can use

plane.quaternion.setFromUnitVectors( Z, normal )
. This optimization avoids trigonometric functions, as explained in this insightful article.

Update 2: It's noted that the direction of the normal vector is crucial. In the implementation, both faces of the plane are rendered to address this. If the plane needs to consistently face away from the origin, make sure to adjust the direction of the normal and the distance to be positive:

if (distance < 0) {
  distance *= -1
  normal.multiplyScalar(-1)
}

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

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Storing data in a JSON format

Our team requires a service that can periodically generate up-to-date JSON data every 15 minutes for our AJAX services to consume. This JSON will be used for metric analysis and charts among other things. The reason behind the 15-minute interval is due to ...

What could be causing the error when attempting to retrieve an index using the window variable?

I'm facing a strange issue where I am trying to utilize a variable that I define as follows: window.params['variable'] = { ... }; Within the function that I am using, the code looks like this: function q() { ... // for example return n ...

Seamless social login integration for registering with Stormpath

Transitioning from C# and PHP to Node.js has presented some challenges, especially when working with the Stormpath API. I am currently trying to integrate social login on the registration page, but the pre-built option only allows it on the Login page. Al ...

What is the best way to access and display the innerText of elements that have been removed using console

When I call the updateCartTotal() function, my goal is to display in the console the items that have been removed from the shopping cart. Every time I click on the remove button, I want it to show the item and the price. However, instead of displaying the ...

Organize elements with jQuery, remove, detach, clone, and append without worrying about memory leaks

I am facing a challenge with a parent div that contains approximately 300 child divs, each one containing an image and some text. I have an array with the necessary information to reorder these divs using references. However, whenever I loop through the a ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

I'm looking to automate a system response whenever a user inputs something - how can I achieve this using NodeJS and Socket

I'm looking to create a feature where, if a user enters a specific command, the socket.io will respond with a predefined message. For example: Input: !hi Output: hello! If anyone knows how to achieve this, I'd appreciate some guidance, tha ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

The triangulation process in Three.js encounters issues when there are nearly identical points present in

Within the realm of three.js, there exists a function called triangulateShape(). Recently, I encountered a challenge while attempting to triangulate polygons that had been simplified using Javascript Clipper. The simplification process in Clipper involves ...

Incorporate various Vue.js components into the main parent component

I am currently utilizing Vue.js to create a user interface for my HTML5 game. I have a scenario where I want to define UI containers that essentially group other UI components and position them on the screen. Here's an example of what I'd like to ...

Having trouble figuring out how to load images into a div based on the current page location?

Looking for a solution to my problem - I have a navigation bar with a fixed div (A) on the far right side. The nav bar remains at the top of the page. There are 6 sections in the body of the page, each being 1200px tall divs. What I want is for a different ...

Best practices for refreshing the HTML5 offline application cache

My website utilizes offline caching, and I have set up the following event handler to manage updates: applicationCache.addEventListener('updateready', function () { if (window.applicationCache.status == window.applicationCach ...