Home > other >  Is it possible to add a rotate animation on an next.js image when clicked?
Is it possible to add a rotate animation on an next.js image when clicked?

Time:12-28

I want to add an animation to an next.js image. It should rotate by 360 degree when clicked one time. I am not able to get the desired result by trying toggle class. I hope someone can help me. Thanks in advance!

CodePudding user response:

import { useSpring, animated } from 'react-spring'

const Image = () => {
  const [animation, setAnimation] = useSpring(() => ({
    transform: 'rotate(0deg)'
  }))

  const handleClick = () => {
    setAnimation({
      transform: 'rotate(360deg)'
    })
  }

  return (
    <animated.img
      style={animation}
      onClick={handleClick}
      src='/image.jpg'
      alt='Animated image'
    />
  )
}

This will create an animation that rotates the image 360 degrees when it is clicked. The useSpring hook returns an object with an animation property that can be used to apply the animation to the image using the style prop.

CodePudding user response:

Using event.target will give you the object that was clicked. Combining that with the CSS transition modifier will rotate elements smoothly.

<body>
    <main>
        <button id="button" style="transition: all 0.5s; background-color: green; width: 100px; height: 50px; border: none; border-radius: 5px; color: lightblue; font-size: 18px" onclick="spin()">click me</button>
    </main>

    <script type = "text/javascript">
        var rotation = 0
        function spin() {
            rotation  = 45;
            event.target.style.transform = "rotate("   rotation   "deg)";
        }
    </script>
</body>
  • Related