Utilize the atan2() function to rotate a div so that it follows the movement of the mouse

I am trying to create an effect where the mouse aligns with the top of a div and the div rotates as the mouse moves. The rotation should happen when the top part of the div is in line with the mouse cursor. My goal is to achieve this using the atan2 function. I envision the end result to be similar to the example found here.

Javascript:

$(function() {
    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;

    $(document).on("mousemove", function(e) {
        // console.log(e.pageX, " ", e.pageY)
        atan = Math.atan2(e.pageY - sTop , e.pageX - sLeft ) 
        console.log(atan)
        stick.css({"transform" : "rotate("  + atan +  "rad)"} )
    })
})

css:

.wrapper{
    width: 500px;
    height: 400px;
    position: relative;
    border:1px solid green;
}
.stick{
    width: 3px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: green;
    transform: rotate(90deg);
}

HTML:

<div class="wrapper">
    <div class="stick"></div>
</div>

Answer №1

I have created a solution that functions correctly and you can view it here.

It appears that the alignment is not being done properly - it is important to consider both the width of the div and the center point of the container.


div.$(function(){

    var stick = $(".stick"), sHeight = stick.outerHeight(), 
                sWidth = stick.outerWidth(), atan,
                sTop = stick.offset().top, sLeft = stick.offset().left;
    $(document).on("mousemove", function(e){
        atan = Math.atan2(e.pageY - 200 , e.pageX - 250) + Math.PI/2;
        console.log(atan);

        stick.css({"transform" : "rotate("  + atan + "rad)" });


    });
});

(I have also eliminated the rotation in the css and placed the stick in the center.)

Answer №2

The issue lies in the calculation of angles with the formula phi=atan2(y,x). This formula assumes a traditional Cartesian coordinate system where the y-axis points upwards. However, in screen coordinates, the y-axis actually points downwards. To correct this, you should use phi=atan2(-y,x).

To confirm, test and observe where the bar is oriented when applying rotations of 0deg and 90deg. In your code, the rotation center is at the middle of the bar, making it challenging to determine orientation accurately. It appears that 0deg points upwards and angles are applied clockwise. Therefore, in an inner coordinate system where 0° represents the X axis and 90° the Y axis, use X = centery-y and Y=x-centerx, resulting in

angle = atan2(x-centerx, centery-y)

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

Javascript selection menu

<body> <script> window.open("http://yourdomain.com:12345/custom/script","_parent"); document.getElementById("dropdown").selectedIndex="2"; </script> </body> Hello, can someone help me troubleshoot my code? My intention is to open ...

Unable to assign an argument to a function in commander.js

Having some trouble passing an option to a custom command in commander.js... program .command('init [options]') .description('scaffold the project') .option('-b, --build', 'add "build" folder with subfolders') . ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Modify a unique element within an array stored in the state using Redux toolkit

I'm currently attempting to modify a property of an object within an array stored in my state. export const changeStatus = createAsyncThunk('changeStatus', async (arg) => { const todo = arg const response = await axios.put(`${URL} ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

Launch a web application utilizing a node.js server hosted on Firebase

I am currently developing a web application using Vue. In this app, I have integrated "pusher" for real-time multi-user communication. I have set up a node.js server on port 5000 of a specific device within my local network. The app functions smoothly with ...

Pattern for validating mobile numbers with extensions using regular expressions

I am struggling to combine multiple separate regex validations into one for my mobile number validation requirements. The criteria include validating mobile numbers with a country code or starting with 00, as well as checking if they contain an extension n ...

Hover effects in CSS animations can be hit or miss, with some working smoothly while others may

Below is the HTML content: <div class="wrapper"> <figure align="center"><img src="http://www.felipegrin.com/port/or-site.jpg" alt=""><br><span>RESPONSIVE HTML5 WEBSITE FOR <br> OR LEDS COMPANY</span></fig ...

Is there a way for me to determine if a user has engaged with a form?

I'm surprised by how difficult it was to find information on this topic through Google. Currently, my struggle lies in wanting my form fields to change color based on validity only after the user has interacted with the form. I don't want invali ...

Is there a way to make two parallelograms overlap seamlessly and adjust in size automatically using HTML?

Recently delving into the world of HTML and CSS, I've set my sights on designing something unique involving parallelograms that adjust dynamically. My vision includes four overlapping parallelograms starting from the top at 25%, 50%, 75%, and finally ...

Exploring Webpack: Unveiling the Contrasts Between Production and Development CSS Bundles

Can you explain the differences in CSS between production and development when compiling with webpack? I've noticed that the production stylesheet seems to consider the entire website, whereas the development mode appears to only focus on the specifi ...

Tips for removing special characters from HTML?

I'm currently grappling with the concept of the filter My situation is as follows: $htmlData includes a user-entered html string formatted like this $htmlData = array('<em>test</em>', 'text here','\n') ...

Despite receiving a 404 fetch response, the page still exists

I have encountered an issue with my Fetch code (POST) where the response shows status: 404 even though the URL returns a JSON when accessed through the browser. Surprisingly, changing the URL to https://httpbin.org/post brings back normal data. Furthermore ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

Cloning dynamic drop downs causing them to malfunction

Currently, I have a table featuring just one row with two drop-down menus. The second drop-down's options are dependent on the selection made in the first drop-down via a JQuery change event. Following the table, there is a button that enables users t ...

Updating every occurrence of a string in the visible text of a webpage: A step-by-step guide

I need to include the registered trademark symbol beside all mentions of a brand, which I'll refer to as "SomeBrand", on a client's website. Here is my current approach: function updateSomeBrand(){ var elements = document.getElementsByTagName( ...

Demonstrate a array of values at varying angles within a circle using the functionalities of HTML5 canvas

Looking to utilize HTML5 Canvas and Javascript for a project where I need to showcase various values (depicted by dots possibly) at different angles within a circle. For example, data could include: val 34% @ 0°, val 54% @ 12°, val 23% @ 70°, a ...