Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translateX, translateY to a certain coordinate rather than a relative point?

My question is about using translateX and translateY in react and/or react-native animations, to animate an object to a certain point.

These two transformations move an object relative to the existing point.

But for the scenario, the existing coordinate is not important and I want to assure the object moves to a certain point wherever it may exist in the screen.

Additional limitation is, I can not animate styles top, bottom, left and right because in react-native, if we animate these styles then we can not use the useNativeDriver={true} directive which causes performance problems.

like image 294
Mehmet Kaplan Avatar asked May 15 '19 12:05

Mehmet Kaplan


People also ask

What are the advantages of using translate () instead of absolute position?

transform causes the browser to create a GPU layer for the element but changing absolute positioning properties uses the CPU. Hence translate() is more efficient and will result in shorter paint times for smoother animations.

What is translateX and translateY?

translateX(n) Defines a 2D translation, moving the element along the X-axis. translateY(n) Defines a 2D translation, moving the element along the Y-axis. scale(x,y)

What does transform translateX do?

The translateX() CSS function repositions an element horizontally on the 2D plane. Its result is a <transform-function> data type.


1 Answers

You can use the onLayout prop to get position (relative to parent) and height/width on any View component.

Something like this should work. You might need to get position of more parent View components, depending on your current structure.

componentDidMount() {
  this.animatedValue = new Animated.Value(0);  
}

animate() {
  const { parentYPosition } = this.state;
  Animated.Timing(this.animatedValue, {
    toValue: FINAL_POSITION - parentYPosition
  }).start(); 
}

render() {
  return (
    <View 
      onLayout={event => {
        const { y } = event.nativeEvent.layout;
        this.setState({parentYPosition: y})
      }}
    >
      <Animated.View 
        style={{
          position: 'absolute',
          top: 0, 
          transform: [
          {
            translateY: this.animatedValue
          }
      />
    />
  );
}

https://facebook.github.io/react-native/docs/view#onlayout

like image 111
Erik Haider Forsén Avatar answered Oct 06 '22 23:10

Erik Haider Forsén