What is the best way to create a shaking image animation using React Native?

I am trying to create a shaking image animation in React Native when a TouchableOpacity is pressed.

So far, I have implemented an animated image with the following code:

const backgroundImage = require('./components/images/baby-sleep.jpg')

class App extends Component {

    constructor(props) {
        super(props)
        this.animatedValue = new Animated.Value(0)
    }

    handleAnimation = () => {
        Animated.timing(this.animatedValue, {
            toValue: 1,
            duration: 1000,
            easing: Easing.ease
        }).start()

    }

This is where I call handleAnimation() within a TouchableOpacity:

<TouchableOpacity onPress={this.handleAnimation}>
   <Text style={{fontSize: 24, fontWeight: 'bold'}}>Play</Text>
</TouchableOpacity>

And here is the code for animating the image:

<Animated.Image
    source={backgroundImage}
    resizeMode='contain'
    style={{

    transform: [
        {
            translateX: this.animatedValue.interpolate({
            inputRange: [0, 1],
            outputRange: [0, 120]
            })
        },
        {
            translateY: this.animatedValue.interpolate({
            inputRange: [0, 1],
            outputRange: [0, 230]
            })
        },
        {
            scaleX: this.animatedValue.interpolate({
            inputRange: [0, 1],
            outputRange: [1, 15]
            })
        },
        {
            scaleY: this.animatedValue.interpolate({
            inputRange: [0, 9],
            outputRange: [1, 150.5]
            })
        }
    ]
    }}
/>

The current code successfully creates an animation when the TouchableOpacity is pressed. However, I am unsure how to implement a shaking effect on the image when the TouchableOpacity is pressed.

Answer №1

You're pretty much there! Below is a complete example for a single wiggle rotation, and you can easily add more animations based on your needs:

const backgroundImage = require('./components/images/baby-sleep.jpg')

class App extends Component {

  constructor(props) {
    super(props)
    this.animatedValue = new Animated.Value(0)
  }

  handleAnimation = () => {
    // A loop is required for continuous animation
    Animated.loop(
      // Animation comprised of a sequence of steps
      Animated.sequence([
        // start rotation in one direction (only half the time needed)
        Animated.timing(this.animatedValue, {toValue: 1.0, duration: 150, easing: Easing.linear, useNativeDriver: true}),
        // rotate in opposite direction, to minimum value (= twice the duration of above)
        Animated.timing(this.animatedValue, {toValue: -1.0, duration: 300, easing: Easing.linear, useNativeDriver: true}),
        // return to initial position
        Animated.timing(this.animatedValue, {toValue: 0.0, duration: 150, easing: Easing.linear, useNativeDriver: true})
      ])
    ).start(); 
  }
}

To apply this rotation to the Image component, add the following:

<Animated.Image
  source={backgroundImage}
  resizeMode='contain'
  style={{
    transform: [{
      rotate: this.animatedValue.interpolate({
        inputRange: [-1, 1],
        outputRange: ['-0.1rad', '0.1rad']
      })
    }]
  }}
/>

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

Error: Attempting to access the 'length' property of an undefined variable in a Google Sheets document

Could someone help me troubleshoot this issue I'm encountering in Google Sheets Apps Script: "TypeError: Cannot read properties of undefined (reading 'length')"? I found this script on YouTube and tried to implement it. Below is the code sn ...

JS: Use either $addToSet or $pull based on the current availability of the value

I am looking for a more efficient way to add or remove an ID from an array (target) in an Articles object, based on whether it already exists. Currently, I am using the following approach: var isExisting = Articles.findOne({ _id }).target.indexOf(mID) > ...

Type Script is throwing an unidentified error being encountered

I am a beginner in Type Script and I'm attempting to convert a small piece of javascript code into typescript, but I keep encountering an error: typeError list[i] is undefined. Here is my original js code: function handleDragStart(e) { this.style.o ...

Tips for implementing React Browser Router within Material UI Drawer

I'm currently exploring how to implement Browser Router in React to populate the content section of a Material UI Drawer. While my code successfully links menu options to components displayed within the drawer's content section, a problem arises ...

Can Angular be used to send form data to an external URL?

Let's take a look at an example with some code: <form method="post" action="URL"> <input type="text" name="first name" /> <input type="text" name="last name"/> <input type="submit" value="Submit" name="submit"/> < ...

Tips for aligning a title to the bottom when its length varies

I am facing a design challenge where I need to align a header with content in a different column. The header's length can vary, so I need to figure out how to align the border-bottom consistently. (The code snippet below is just for illustration pur ...

Firebase not displaying events properly

I have configured Firebase and Google Tag Manager to track hits on both Firebase and Google Analytics. Despite setting up Google Analytics tags successfully, I am not seeing any activity on the Firebase console. When data is sent from Android to Firebase, ...

Error: The URI you are trying to access is restricted and access has been denied

I'm facing an issue with my HTML file that contains multiple d3-graphs embedded directly within script tags. When I try to move one of the graphs to an external JavaScript file, I receive the following error message: "NS_ERROR_DOM_BAD_URI: Access to r ...

Creating a responsive YouTube video embed within a div container with a fixed background image

Hello there, I'm currently working on positioning the YouTube Iframe on the background to make it look like the video is playing on a laptop screen. I also want it to scale down appropriately with the background image on different resolutions. The w ...

Enhancing User Experience with Interactive React Hover Effects

Hello, I have tried various combinations but still cannot get the desired background color to display when hovering over my <p> element. I am looking for a CSS-only solution and not interested in using JavaScript hover events. I would appreciate it ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

Is there a way to adjust text animations so they appear separately in their designated space?

During my project, I decided to incorporate some CSS animations onto the site. However, I encountered a problem with the overflow: hidden attribute not functioning as anticipated. Here is the code snippet I used: .jumbotron { height: 100%; heigh ...

Show the layout of the table in a visual format

I am struggling to showcase a table created using <ul> tags. I want the content to be displayed one after the other. Here is my code: CSS .activity-list-header > li { display: inline-block; text-align: left; width: 15.666%; list- ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : https://i.sstatic.net/pQP79.png My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintai ...

Utilizing Webpack and Typescript for an enhanced DataTables experience: A bespoke JQuery Plugin

I am currently facing an issue while trying to integrate the datatables JQuery plugin with webpack and typescript. While I have successfully set up JQuery with typings and intelliSense, the datatables integration seems to be causing issues. After building ...

The xpath identifier in Selenium Python 2.7 for Chrome is dynamically changing with each instance

I have encountered another issue. I previously asked a similar question and tried the suggested method, but it did not work for this specific problem. The HTML code for this element is related to Filters. The main issue is that there is a toggle button th ...

Is it possible to have the website show up at a default size of 90% on the display

My preference is for my website to appear at 90% instead of 100%. This seems to be a common occurrence for me. Is there a way to have it default to this appearance? ...

Utilizing JavaScript to showcase information retrieved from the database

After implementing this code example for a cascaded drop-down menu, I would like to incorporate the names of individuals residing in a specific city. How can I achieve this functionality once a city is selected? Demo link: Complete code snippet below: ...

Is there a way to programmatically emulate Firebug's inspect element feature using JavaScript?

Is there a straightforward method in JavaScript or any popular libraries like YUI or jQuery to allow users to interact with elements on a website, similar to the functionality of Firebug for developers? ...