Rotate an image based on the movement of the mouse cursor

The following code snippet demonstrates how to rotate an image element using jQuery:

$(document).ready(function(){
    var player = $('#player');
    
    $(window).on('mousemove', function (e) {
        var p1 = {
            x: player.offsetLeft,
            y: player.offsetTop
        };

        var p2 = {
            x: e.offsetX,
            y: e.offsetY
        };

        var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;

        if(angleDeg >= 360){
            angleDeg -= 360;
        }

        player.css('-webkit-transform', 'rotate(' + angleDeg + 'deg)');
    });
});

However, the rotation does not occur as expected. Alternatively, when utilizing the code below, the image will follow the mouse cursor:

$(document).mousemove(function(e){
    $("#player").css({left:e.pageX, top:e.pageY});
});

It seems like I am only able to move the image rather than rotate it. For a live demonstration, please visit this JSFiddle link.

Your assistance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

Adjusting Offset in jQuery

If you need to access the offsetLeft and offsetTop properties using jQuery, make sure to use player.offset().top and player.offset().left. For more details, refer to the jQuery documentation on the offset function. Attempting to directly access the offsetLeft or offsetTop property could result in undefined values, causing issues with angle calculations.

Correcting Image Orientation

After addressing the offset issue, you may notice that the image pointing direction is incorrect (off by 90 degrees). To fix this, consider adjusting the rotation of the image file itself or incorporating a correction into the angle calculation function.

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

Struggling to identify which css or bootstrap statement is impacting the arrangement of the form layout

I'm facing an issue with setting a border and background color behind a form. When I attempt to do so, the form is aligned to the right and I can't pinpoint which part of my code is causing this misalignment. Here's an example: https://jsfi ...

Incorporating an image into a cell within a jqxgrid

I recently utilized Jqxgrid in a project where I was able to load data from a JSON string into the grid successfully. Now, I am looking to add images/icons in a column cell for each specific entry/row. Below is the code snippet that initializes the grid: ...

Is it possible for Google to crawl and index a website that has minified HTML and CSS?

After creating a Bootstrap website, I noticed that the HTML file is nearly 400kb in size, making it slow to load on mobile devices. To address this issue, I am considering using the tool to minify the code. Will Google be able to properly index a we ...

Combine a segment from two arrays into a single array

I have two arrays and I want to merge them into one while extracting only certain elements... I am using axios with vueJS. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: Nombredejours: 1.5 Task: {id: "52edcb0e-450f-4de7-b70d-b63e0 ...

When the font size is set below 16px on an iPhone, iOS will automatically zoom in to compensate

Currently, I am running tests on my app using an iPhone. Everything seems to be working correctly on the iPad, but when I try clicking on a text field on the iPhone, the view automatically zooms in. It appears that setting the font size to 16px or larger r ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

What is the best way to display items within a table using React?

I'm just starting to learn React. Can someone show me how to use the "map" function to list elements from two different arrays in two columns? state = { dates: ["2000", "2001", "2002"], cases: ["1", "2", "3"] } render() { return ( <thea ...

unable to utilize react-speech-recognition package

Looking for a simple react package that can convert user audio to text? I recently installed one and tried its basic code example, only to encounter an error message stating "RecognitionManager.js:247 Uncaught ReferenceError: regeneratorRuntime is not defi ...

Trouble extracting data with XPath query in Python

Currently, I am attempting to extract specific information from this particular webpage. However, there are three crucial pieces of data that have proven to be quite elusive. Firstly, I am struggling to retrieve the grade, denoted by '5.6' next ...

I keep receiving the message "Error 404 - Page not found". Any suggestions on what steps to take

**I just started learning Django and I'm facing an issue. Every time I try to open/click on the list/entries, I get a "PAGE NOT FOUND" error message. Here are the files in my "entries" folder: Css.md Django.md Git.md Python.md HTML.md** Here is ...

Directional Div CSS Transition

Is it feasible to determine the starting direction of a CSS transition? I've designed a div that enlarges in height when hovered over; however, it's situated at the bottom of the page, causing the scrollbar to extend downward. Ideally, I would ...

Ways to determine whether one side of a selected div is not obstructed by other divs

I am working with some div elements that are all sized 100x100px: Below is the HTML code for the 3 blocks: <div id="plane"> <div class="tile tile3" block-id="1" style-id="3" style="left:50px; top:50px"></div> <div class="tile t ...

Tips for avoiding node js from exposing .git directories and its contents

I understand that by using a .htaccess file, I can restrict files from being served under .git. However, I am unsure of how to achieve the same functionality when using a node.js server. I typically use forever to start and stop the servers. Below is the ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

Ensure that the CSS grid has a minimum span of 3 columns, and if a class object is the only item in a grid row, it

I am currently utilizing CSS grid to create the layout for my web application. I need to specify that a particular class should have a minimum grid-column span of 3 frames and extend across the entire grid row if it is the only object in that specific row. ...

Enhancing Efficiency with Laravel 5: Updating Multiple Data Entries

My Simple Todo App lacks the ability to persist multiple record updates simultaneously. The client-side version can be found here: http://codepen.io/anon/pen/bVVpyN Whenever I perform an action, I send an HTTP request to my Laravel API for data persistenc ...

What is the best way to have a sound play when the page is loaded?

Is there a way to automatically play a sound when the page loads? <audio src="song.mp3"> Your browser does not support the audio element. </audio> I've attempted it with the following method: <script type="text/javasc ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...