So I'm trying to implement a draggable circle which can be moved up an down randomly inside a svg-element. I am using the Svg-element from react-native-svg and inside I have multiple of the following custom component:
const panGestureHandler = useAnimatedGestureHandler({
onStart: (event, context) => {
context.translateY = translateY.value;
console.log("start");
},
onActive: (event, context) => {
console.log(event.translationY);
let tmp = event.translationY + context.translateY;
if (posY + tmp >= svgHeight) {
translateY.value = svgHeight - posY;
} else if (posY + tmp <= 0) {
translateY.value = -posY;
} else {
translateY.value = tmp;
}
},
onEnd: (event, context) => {
console.log("end");
},
});
const translateStyle = useAnimatedStyle(() => {
return {
transform: [
{
translateY: translateY.value,
},
],
};
});
return (
<PanGestureHandler onGestureEvent={panGestureHandler} style={translateStyle}>
<AnimatedCircle
cx={posX}
cy={posY}
r={radius}
fill={color}
stroke={color}
style={translateStyle}
animatedProps={strokeAnimation}
/>
</PanGestureHandler>
);
The onActive inside panGestureHandler should prevent the dragging outside of the svg.
AnimatedCircle is an animated component from react-native-reanimated and implemented like this:
import { Circle } from "react-native-svg";
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
However, most of the time the dragging only works on the element created last (created while iterating over an array) and once moved up or down, it cannot be moved anymore.
But if I drag the circle somewhere and then place it at its start-point, I can drag it again.
Trying it without the style on the PanGestureHandler yields the same result btw.
Any help is appreciated :)