Skip to content

Instantly share code, notes, and snippets.

@flunder
Created December 5, 2020 20:56
Show Gist options
  • Save flunder/dee68e921820615975588dfb1989da62 to your computer and use it in GitHub Desktop.
Save flunder/dee68e921820615975588dfb1989da62 to your computer and use it in GitHub Desktop.
React Native test of Reanimated2
import React, { useEffect, useRef } from "react";
import { Dimensions, View } from "react-native";
import Animated, { useSharedValue, withTiming, useAnimatedStyle, useAnimatedProps } from "react-native-reanimated";
import Svg, { Polygon } from 'react-native-svg'
const { width, height } = Dimensions.get('window');
const MAXBALLS = 100;
const BALL_SIZE = 10;
const ballsArray = [...Array(MAXBALLS)];
const AnimatedPolygon = Animated.createAnimatedComponent(Polygon);
export default function MovingBall3(props) {
const isRunning = useRef(false);
const locations = ballsArray.map((_, i) => {
return {
locX: useSharedValue(width / 2),
locY: useSharedValue(height / 2)
}
})
const animatedStyles = ballsArray.map((_, i) => {
return useAnimatedStyle(() => {
return {
transform: [
{ translateX: locations[i].locX.value },
{ translateY: locations[i].locY.value },
]
}
})
})
const connections = useAnimatedProps(() => {
return {
points: ballsArray.map((_, i) => {
return `${locations[i].locX.value}, ${locations[i].locY.value}`
}).join(' ')
}
})
const animateMe = () => {
ballsArray.map((_, i) => {
locations[i].locX.value = withTiming(Math.random() * width, { duration: 1000 });
locations[i].locY.value = withTiming(Math.random() * height, { duration: 1000 });
})
setTimeout(animateMe, 1000);
}
useEffect(() => {
if (isRunning.current === true) return; // Bypass fastRefresh
animateMe();
isRunning.current = true;
}, [])
return (
<View>
<Svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<AnimatedPolygon
// points={connectionsPath.value}
animatedProps={connections}
stroke="black"
strokeWidth="2"
/>
</Svg>
{[...Array(MAXBALLS)].map((_, i) => (
<Animated.View key={i} style={[
{ position: 'absolute', width: BALL_SIZE, height: BALL_SIZE, top: -BALL_SIZE/2, left: -BALL_SIZE/2, backgroundColor: 'black', borderRadius: 100 },
animatedStyles[i]
]} />
))}
</View>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment