Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way:

.foo {
  transform: rotateX(-30deg) rotateY(35deg);
}

Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple:

var matrix = $('.foo').css('transform');
// returns:
// matrix3d(0.819152, -0.286788, -0.496732, 0, 0, 0.866025, -0.5, 0, 0.573576, 0.409576, 0.709406, 0, 0, 0, 0, 1)

The challenge lies in calculating CSS values like -30 and 35 from that matrix. While methods exist for 2D transforms, a solution for 3D rotation remains elusive.

Answer №1

Sure, understood!

const _fetchTransform = function($element) {

    let matrix = $element.css('transform'),
        rotateX = 0,
        rotateY = 0,
        rotateZ = 0;

    if (matrix !== 'none') {

        // perform some calculations
        let values = matrix.split('(')[1].split(')')[0].split(','),
            pi = Math.PI,
            sinB = parseFloat(values[8]),
            b = Math.round(Math.asin(sinB) * 180 / pi),
            cosB = Math.cos(b * pi / 180),
            matrixVal10 = parseFloat(values[9]),
            a = Math.round(Math.asin(-matrixVal10 / cosB) * 180 / pi),
            matrixVal1 = parseFloat(values[0]),
            c = Math.round(Math.acos(matrixVal1 / cosB) * 180 / pi);

        rotateX = a;
        rotateY = b;
        rotateZ = c;

    }

    return {
        rotateX: rotateX,
        rotateY: rotateY,
        rotateZ: rotateZ
    };

}

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

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

Bulma: Tips for creating equally sized buttons?

I am working with Bulma CSS and trying to ensure that all my buttons are the same size. Currently, each button appears to have a different size based on the text content. I have looked into using the "is-fullwidth" option, but it makes the buttons too la ...

Suggestions on how to refactor redundant code in various peer AngularJS controllers for handling $intervals

In my compact single-page application, I have implemented multiple tabs to display operational status information for different applications. Each tab is associated with a controller that creates $interval objects to make AJAX calls to fetch status data fr ...

Creating a Three-Row Table with Material-UI and React

I am looking to achieve a layout similar to the one shown in the image below: I want to construct a table with three rows, where the third row is positioned below the first and second rows, and the width of the third row is equal to the combined width of t ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

The functionality of the click event attached with the addEventListener is

I have a unique project where I am developing a user interface for a paper-rock-scissor game. To create the UI, I included four buttons: "Start game," "rock," "paper," and "scissor." Initially, I wrote separate code for each button, which worked perfectly ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...

Is it possible to programmatically bind a click event to each individual word in a div element?

I'm attempting to link each word within an element without altering the markup inside the element using Javascript. ...

Can the operator pipeline generate interim observables in a manner akin to how filter, map, and reduce generate interim arrays?

I need some clarification regarding the efficiency of operator pipelines in RxJS. Based on my current understanding, each operator within the pipeline receives an observable and generates a new (potentially modified) observable to pass on to the next oper ...

Tips for generating a universal regulation in vee-validate version 3

Is it possible to create a universal validation rule that can be applied to multiple elements? universalRule: { required:'required', min:'min', etc.. } On the form <ValidationProvider name="universalRule" rules=&qu ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...

External CSS file for Demandware platform

My boss was supposed to train me this year on demandaware knowledge, but ended up quitting, leaving me in the dark. I am scheduled to attend workshops later this year, but for now I am relying on Google and stackoverflow for guidance. Currently, I am wor ...

Creating parallel lines utilizing pseudo elements

Can someone assist me in drawing double lines under my paragraph using pseudo elements only without using display block? Here is my code snippet with display block: p:after { content: ""; display: block; width: 40px; margin: 20px auto 0; bord ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Is it possible to convert a date that has been set using useState into an ISOString format?

I am currently working on a project using NextJs. One of the issues I am facing involves creating activities for users on a page using useState and fetch POST. Although most things seem to be functioning correctly, I am experiencing difficulties with handl ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

"Escaping from the typeahead feature in Angular-UI Bootstrap results in the input field value becoming

Having some difficulty solving a particular edge case scenario. When I select a value from the dropdown of the typeahead using either the keyboard or mouse, the ng-model in the input field is populated correctly. However, if I type a few letters and then ...

What is the best way to populate all data in select2 (4.0) upon page load?

I'm currently utilizing the select2 plugin (v.4.0) and have a specific goal in mind: $("#search-input-chains").select2({ placeholder: "Unit", theme: "bootstrap4", ...