What is the method for obtaining the angle in a CSS3 rotate transformation?

In my current code, I am setting the rotational angle of an element using the following:

$('#1-link-2')
                .css('height', length)
                .css('-webkit-transform', 'rotate(' + angle + 'deg)')
                .css('-moz-transform', 'rotate(' + angle + 'deg)')
                .css('-o-transform', 'rotate(' + angle + 'deg)')
                .css('-ms-transform', 'rotate(' + angle + 'deg)')
                .css('transform', 'rotate(' + angle + 'deg)');

The angle is calculated dynamically based on the mouse position.

Now, I want to retrieve the angle. I attempted this:

var angle= $("#1-link-2").css('-webkit-transform');
    $('#node-title').html(angle);   //displaying it on the screen

The output I received was:

matrix(0.5425908601788315, -0.839997118120292, 0.839997118120292, 0.5425908601788315, 0, 0)

How do I extract the angle in degrees from this?

Answer №1

When dealing with rotation angles, the first value corresponds to the cosine, and the second value corresponds to the sine - provided there are no additional transforms applied to the element. Utilize your preferred mathematical library to compute inverse sine and cosine functions.

For instance, the inverse cosine of .54 equates to around 54 or 306 degrees. Similarly, the inverse sine of -0.83 is approximately 234 or 306 degrees.

It seems like the correct answer consistently amounts to 306 degrees.

If you need a geometry refresher, you can find one here.

Answer №2

Take a look at this helpful article:

const element = document.getElementById("elementID");
const styles = window.getComputedStyle(element, null);
const transformValue = styles.getPropertyValue("-webkit-transform") ||
         styles.getPropertyValue("-moz-transform") ||
         styles.getPropertyValue("-ms-transform") ||
         styles.getPropertyValue("-o-transform") ||
         styles.getPropertyValue("transform") ||
         "FAIL";

// Example with rotate(30deg)...
// matrix(0.866025, 0.5, -0.5, 0.866025, 0px, 0px)
console.log('Matrix: ' + transformValue);

// Extracting values from the matrix
const matrixValues = transformValue.split('(')[1].split(')')[0].split(',');
const a = matrixValues[0];
const b = matrixValues[1];
const c = matrixValues[2];
const d = matrixValues[3];

const scaleValue = Math.sqrt(a*a + b*b);

console.log('Scale: ' + scaleValue);

// Calculating the rotation angle
const sinValue = b/scaleValue;
const angle = Math.round(Math.atan2(b, a) * (180/Math.PI));

console.log('Rotation Angle: ' + angle + 'deg');

Answer №3

const calculateRotation = (element) => {
  const matrix = element.css("-webkit-transform") ||
                 element.css("-moz-transform") ||
                 element.css("-ms-transform") ||
                 element.css("-o-transform") ||
                 element.css("transform");
  
  if (matrix !== 'none') {
    const values = matrix.split('(')[1].split(')')[0].split(',');
    const a = values[0];
    const b = values[1];
    let angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    return (angle < 0) ? angle + 360 : angle;
  } else {
    return 0;
  }
}

let angle1 = calculateRotation($('#1-link-2'));

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

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

Loop through a CodeIgniter database result object using Ajax

Hey there, I could really use your expertise on this one. I'm working with Codeigniter and my model is returning a database result object (not an array) to the controller. I need to iterate through this object using Ajax. Any suggestions on the best w ...

Incorporating Redis within an Express route

My goal is to store a value in a specific key in one route: /api/foo?redisKey="1" (setting value for the key id=1) Then, in another route, I want to retrieve the value: /api/bar?redisKey="1" (getting value for key id=1) Since redis operates asynchronou ...

Is there a way to retrieve the xpath count in Selenium WebDriver through Jasmine JavaScript?

var elementCount = browser.findElements(driver.By.xpath('//somenode')).getXpathCount(); console.log( elementCount.intValue() ); Whenever I try to print the count, I encounter this error: Error occurred - TypeError: undefined is not a function ...

Encountering an unspecified variable in Sass

I am a beginner in the world of sass and I am trying to incorporate a variable from a file named "_designs.scss" into another file called "_component.scss". Despite my efforts, I keep encountering an "Undefined variable: $grey-light-2" error. I have exhaus ...

The function does not generate an image, but it will display the one that is

It looks like there may be an issue within the function that is preventing the image from being created, or possibly in the script itself which is not passing the image to the function properly. Below is the upload script (please note: this script is inje ...

Manage multiple sessions at the same time

In a specific scenario, we face the need to manage multiple sessions similar to Google Accounts. Users should be able to add different accounts in separate tabs, each with its own unique content. For example, user1 may be logged in on Tab1 while user2 is l ...

Expanding worldwide mixin in Nuxt.js

Currently, I am working with Nuxtjs version 2.15.7 and have a mixin file structured like this: utils.js : import Vue from "vue" if (!Vue.__utils__) { Vue.__utils__ = true Vue.mixin({ data(){ return{ ... } }, ...

Detect and switch the value of a CSS selector using Javascript

Incorporating the subsequent jQuery code to insert CSS styles into a <style id="customizer-preview"> tag within the <head>: wp.customize( 'site_title_color', function( value ) { value.bind( function( newval ) { if ( $( &a ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...

Creating endless scroll feature in Vuetify's Autocomplete component - A comprehensive guide

Having trouble with my Vuetify Autocomplete component and REST API backend. The '/vendors' method requires parameters like limit, page, and name to return JSON with id and name. I managed to implement lazy loading on user input, but now I want i ...

Trouble with background image displaying on meteor platform

Hey there! I'm in the process of replicating the HBO login page without functional links, but for some reason, the background image isn't loading properly. I suspect it might be an issue with resizing the image, but I can't pinpoint the exac ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...

to streamline the process of navigating Google Chrome web pages

Is it possible to create automation in Google Chrome that can complete the following tasks: 1. Input a job name to monitor 2. Periodically click a refresh button on the webpage (not the refresh button for the entire Chrome page in the left corner) 3. Open ...

Indent the text within a span element that is displayed as an inline block

I am in search of a solution using only CSS for the following issue. Take into account the HTML below: <p> <span>Some text</span> <span>Some text</span> </p> Both <span> elements are set as inline-block. ...

Making a single variable object as opposed to using multiple variables

In order to improve the code structure, I am looking to consolidate all properties into a JavaScript object instead of using multiple variables: // Method 1 // This method gives an error as _inp cannot be accessed by input_value // Uncaught TypeError: Can ...

Create a division element with an image that can be dragged around

I'm having trouble making a div element draggable. Inside the div, there is an img and some text that acts as a label for the image. The issue is that when I begin dragging by clicking on the img, it's the img that gets dragged instead of the par ...

Is it possible to further simplify this piece of JavaScript using jQuery?

In my journey to learn and grow with Javascript, I have come across a snippet of code that simply attaches an onclick event to a button and updates the text of an em tag below it. As I delve deeper into jQuery, I am beginning to appreciate its syntax and u ...

The functionality of jQuery autocomplete is hindered when trying to utilize a remote data source

HTML: <input type="text" id="shop-id"> JS: $(document).ready(function(){ $( "#shop-id" ).autocomplete({ source: "/ticket/get_sids", select: function(event, ui){ //... } }); }); Encountering an unusual i ...

I'm having trouble getting my flex items to maintain a specific width and height while staying in a single line

I've been out of practice with flexbox for some time and I can't figure out why the width and height properties are not being applied to each flex item as expected. All the items seem to have an equal width, but not the width that I specified. Ad ...