javascript - 动画 React-native-svg

标签 javascript react-native react-native-svg

我正在尝试通过以下代码为 SVG 制作动画:

//create animated path component

const AnimatedPath = Animated.createAnimatedComponent(Path);

  P1 = new Animated.ValueXY({x: 0, y: 1});
  P2 = new Animated.ValueXY({x: 1, y: 1});
  P3 = new Animated.ValueXY({x: 2, y: 1});
  path = `M ${this.P1._value} ${this.P1._value} S ${this.P2.x._value} ${this.P2.y._value} ${this.P3.x._value} ${this.P3.y._value}`;

            Animated.timing(this.P1, {
              toValue: {x: 3, y: 3},
              duration: 300,
              useNativeDriver: 'true',
            }).start();


        <Svg height="50%" width="50%" viewBox="0 0 4 4 " fill="blue">
          {/* <Path /> */}
          {console.log('this.P1.x: ', this.P1.x)}
          <AnimatedPath
            d={this.path}
            // d="M 0 1 S 1 1 2 1"
            fill="none"
            stroke="red"
          />
        </Svg>

但它不起作用。有什么办法让它变得动画吗?
我们还应该使用react-native-reanimated2吗?

最佳答案

检查 reanimated2 文档中的 useAnimatedProps 。 请注意,记录的示例有一些缺陷,这里是一个演示:

import { StyleSheet } from 'react-native';
import {
  Animated,
  useSharedValue,
  useAnimatedProps,
  withTiming
} from 'react-native-reanimated';
import Svg, { Path } from 'react-native-svg';

const AnimatedPath = Animated.createAnimatedComponent(Path);

function App() {
  const radius = useSharedValue(50);

  const animatedProps = useAnimatedProps(() => {
    // draw a circle
    const path = `
    M 100, 100
    m -${radius}, 0
    a ${radius},${radius} 0 1,0 ${radius * 2},0
    a ${radius},${radius} 0 1,0 ${-radius * 2},0
    `;
    return {
      d: path
    };
  });

  // attach animated props to an SVG path using animatedProps
  return <Svg><AnimatedPath animatedProps={animatedProps} fill="black" onPress={() => radius.value = withTiming(Math.random() * 180)} /></Svg>
}

我知道您可能找到了解决方案,但我想为偶然发现此问题的人提供答案。

关于javascript - 动画 React-native-svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63934357/

相关文章:

javascript - 如何在js中访问svg元素的描述?

javascript - 根据当前时间更改滚动标题

ios - xcodebuild 失败,返回码为 : 65 - using CLI/Appcenter but no error messages

android - 使用ScrollView出现这个异常: com. Facebook。 react 。管理器。事件。 TouchEventCoalescingKeyHelper。获取合并 key

javascript - 新的 react native 元素无法访问

reactjs - React Native SVG - 设置 SVG 宽度和高度会导致图标被截断

react-native - React Native svg 未正确渲染

javascript - 按钮的点击监听器在 Bootstrap 中不起作用

javascript - 使用 SSL 运行的应用程序在第一次访问时未加载所有脚本/CSS

reactjs - react-native-svg onPress 事件不工作