Can a seamless CSS transition be achieved at 0 degrees using transform:rotate(Xdeg)?

I am working on a React application that includes an icon positioned on a Leaflet map. The icon has a value ranging from 0 to 359 to represent its current direction.

My goal is to use transform: rotate(Xdeg) to rotate the icon and implement a smooth animation using transition.

However, I encountered an issue where when the value reaches either 0 or 360, the transition occurs in the opposite direction.

Is there a way to smoothly transition a box with transform: rotate(340deg) to transform: rotate(10deg) in a clockwise rotation?

Check out an example on CodePen here

const App = () => {
  const [rotation, setRotation] = React.useState(340);

  return (
    <div id="wrapper">
      <div>
        <div className="box-wrapper">
          {/* Dynamic CSS transform for rotating the box */}
          <div className="box" style={{ transform: `rotate(${rotation}deg)` }}>
            <span>{ `Rotation: ${rotation}deg` }</span>
          </div>
        </div>
      </div>

      <div>
        <button onClick={() => setRotation((rotation + 10) % 360)}>+10 deg</button>
        <button onClick={() => setRotation(((360 + (rotation - 10)) % 360))}>-10 deg</button>
        <button onClick={() => setRotation(340)}>340 deg</button>
        <button onClick={() => setRotation(20)}>20 deg</button>
      </div>
    </div>
  )
}

Answer №1

The reason for the "spinning" effect is due to the use of a modulo operator in your calculation. The flipping occurs every time you reach the boundaries of 0 or 359. To resolve this issue, consider removing the modulo operator from your calculation and using it solely for displaying the degree value.

I have made some modifications to your CodePen link.

const App = () => {
  const [rotation, setRotation] = React.useState(340);
  function setRotation1(val) {
    let angle = rotation % 360;
    let diff = (360 - (angle - val))%360;

    if(diff > 180) {
      diff = (360-diff);
      setRotation(rotation - diff);
    } else {
      setRotation(rotation + diff);
    }
  }

  return (
    <div id="wrapper">
      <div id="demo">
        <div className="box-wrapper">
          {/* Setting the rotation CSS transform dynamically */}
          <div className="box" style={{ transform: `rotate(${rotation}deg)` }}>
            <span>{ `Rotation: ${(360+(rotation%360))%360}deg` }</span>
          </div>
        </div>
      </div>

      <div>
        <button onClick={() => setRotation(rotation + 10)}>+10 deg</button>
        <button onClick={() => setRotation(rotation - 10)}>-10 deg</button>
        <button onClick={() => setRotation1(340)}>340 deg</button>
        <button onClick={() => setRotation1(20)}>20 deg</button>
      </div>
    </div>
  )
}

Note: I have revised the code based on discussions in the comments section.

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

After modifying the variable from 'let' to 'const' and replacing 'i++' with 'i+1' in

After some time of coding without tslint, I decided to enable it again. Upon doing so, I noticed some errors and promptly fixed them. I made the following change: for (const index = 0; index < combinedUniqueIndexes.length; index + 1) However, after m ...

Encountered an error when attempting to use 'appendChild' on 'Node': the first parameter is not the correct type. It was able to work with some elements, but not with others

I'm currently working on a script that utilizes fetch to retrieve an external HTML file. The goal is to perform some operations to create two HTMLCollections and then iterate over them to display a div containing one element from each collection. Here ...

What tag would allow me to seamlessly customize the text language choice on a website using CSS to my liking?

Here are two HTML snippets for allowing the user to choose a language: One uses <select> and <option>s, The other uses a <div> with alternating <input>/<label>s. I plan to select one of these methods (or find a better one) a ...

Error in Nestjs Microservices: Local server not updating with code changes

I am diving into the world of Nestjs microservices with the latest versions - Nest Version 9.0 and Node Version 16.0. Currently, I have set up a service and am in the process of tweaking the code. App.module.ts @Module({ imports: [], controllers: [Ap ...

Tips for clearing cache in Node.js during an HTTP GET request

Currently, I am developing a node.js web application in which I am utilizing an HTTP GET request to access a database and retrieve data via a query. While the HTTP GET request functions properly on Chrome, I am encountering an issue on Internet Explorer w ...

Using CSS to resize an element with both dimensions while maintaining its

Is it feasible to preserve a 1:1 aspect ratio on a div element using the CSS resize property? This particular illustration lacks an aspect ratio. Do you have any recommendations? ...

Activate the angular function

In the controller below, there is a function that should be triggered when the link is clicked: <a id="1" href="" name="xxx" ng-click="searchall(id)">sample link</a> ng.controller('SearchResultController', ['$scope', &apos ...

What is the best way to list all Docker containers, including those that are not currently active?

I am currently working on adding a button that will initiate all the inactive containers. I am using Dockerode to accomplish this task, as I have successfully implemented a similar function to stop all containers. However, while trying to start the contai ...

Leveraging multiple routes for a single component in Angular 6

Creating a component named Dashboard for admin requires passing the username in the route to find user information. This is the routing setup: {path:'dashboard/:username',component:DashboardComponent,children:[ {path:'role',component: ...

Guide on displaying link parameter information on a separate webpage using only JavaScript

While doing some research, I came across an issue. I have a page called specifications.html with three links: details.html?id=1, details.html?id=2, and details.html?id=3. My goal is to display the details of each link when someone clicks on it. For examp ...

Every time I attempt to bootstrap AngularJS and RequireJS, I consistently encounter a dependency injection issue

Recently, I've been working on a single page application using requirejs and angularjs. While I managed to load all the necessary files and run the app smoothly without any conflicts or dependencies from other angular apps, I encountered an error when ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Having issues with rendering my images on Nuxt framework

In the midst of configuring the routing for my Nuxt project, I've encountered challenges with nesting specific folders to achieve a route structure like this: "/PageAccueil/PricingPage/Checkout123". The issue arises when attempting to place the "Pric ...

What are the secrets to creating a high-class look?

Can the code <a href="link"><span class="metalink">text</span></a> be adjusted to only apply the link style without the class? The use of !important is not effective. ...

The attempt to fetch an additional 10 items through an AJAX call failed to meet expectations

I want to implement a feature where 10 items are loaded each time the "load more" button is clicked. Initially, I send the first 10 items and use dajaxice to load another set of 10 items everytime the button is pressed. Below is my view: def dj(request, ...

Showing JSON information in Cytoscape.js

I am currently working on a Java Web Application where I need to generate a graph programmatically and send it to Cytoscape.js (version 2.7.10) for display. In order to transport the data from my application to Cytoscape.js, I am using gson (version 2.8.1) ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

Centering SVGs with absolute positioning - Maintaining aspect ratios

Here is the code I am working with: http://jsfiddle.net/uorto4ny/2/ The challenge I'm facing is trying to keep a fluid sized SVG centered on the page while maintaining its proportions. Currently, it works in Chrome, but in IE and Firefox, one side of ...

manipulating an iframe on a separate domain

Currently, I am in the process of creating a mobile app using the Ionic framework for my website. Nevertheless, I believe that the issue at hand is not exclusive to Ionic. My goal within the app is to showcase a full-width, full-height iframe loading a sp ...

"Utilizing CSS to ensure a div adheres to a specific class

I'm trying to change the floating position of a div by using a CSS class, instead of its predefined properties. Currently, the div is styled as follows: #div { height: 30px; width: 30px; float:left;} To make it float to the right, I created a class ...