I have the following code to animate in React Native
Animated.timing(
this.state.absoluteChangeX,
{toValue: 0},
).start(function() {
this.lastX = 0;
this.lastY = 0;
});
Pretty simple, but whenever it's triggered, I receive the error:
singleValue.stopTracking is not a function
Here's where the error originates:
/react-native/Libraries/Animates/src/AnimtaedImplementation.js
var timing = function(
value: AnimatedValue | AnimatedValueXY,
config: TimingAnimationConfig,
): CompositeAnimation {
return maybeVectorAnim(value, config, timing) || {
start: function(callback?: ?EndCallback): void {
var singleValue: any = value;
var singleConfig: any = config;
singleValue.stopTracking(); // <--------------- HERE!!!
if (config.toValue instanceof Animated) {
singleValue.track(new AnimatedTracking(
singleValue,
config.toValue,
TimingAnimation,
singleConfig,
callback
));
} else {
singleValue.animate(new TimingAnimation(singleConfig), callback);
}
},
stop: function(): void {
value.stopAnimation();
},
};
};
I'm not extremely versed in typeScript, but var singleValue: any means that "singleValue" could be any type. In my case, it's a number. Since numbers don't have methods, it would make sense that this would error.
Am I doing something wrong?
The value you wish to animate must be an instance of Animated.Value, or one of its subtypes. When you initialize your state, it should look something like this:
getInitialState() {
return { absoluteChangeX: new Animated.Value(0) };
}
The fact that the type declaration in the framework method is any is just a lack of constraint, not an explicit invitation to pass any value into it.
See the Animated docs for more examples.
I run into this issue sometimes (React hooks instead) when I forget to set my variable to the .current of the ref:
function MyComponent() {
const animatedValue = useRef(new Animated.Value(0.0)).current; // Notice the .current
}
This may not necessarily answer the original question, but developers who encounter this error while using React hooks may end up here so maybe it will help someone.
I ran into this issue because I used the animated value (2) instead of the object (1):
const animatedValue = useRef(new Animated.Value(0.0)).current; // (1)
const transform = animatedValue.interpolate({
inputRange: [0.0, 1.0],
outputRange: [0, 100]
}); // (2)
Animated.timing(animatedValue, { // USE animatedValue, NOT transform HERE!
toValue: 1.0,
duration: 3000,
});
Hope this can help anyone that was new to React Native Animation (like me :) )...
Related
Here is an open GitHub issue Github Issue
Here is a Expo Snack
For some reason, variables are not incrementing inside the canvas function while outside works just fine. Please have a look at my code:
function home ({ navigation }) {
const [counter, setCounter] = useState(330);
useEffect(() => {
const timeout = setTimeout(() => {
setCounter(counter + 1);
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [counter]);
console.log('outside ', counter);
const _onGLContextCreate = (gl) => {
var ctx = new Expo2DContext(gl);
// setInterval(() => {
// console.log('set interval doesnt refresh too ', counter);
// }, 1000);
console.log('inside ', counter);
let circle = {
x: counter,
y: 100,
radius: 30,
color: 'black'
}
let circle2 = {
x: 400,
y: 100,
radius: 30,
color: 'blue'
}
function drawCircle() {
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
ctx.fillStyle = circle.color;
ctx.fill();
ctx.closePath();
}
function drawCircle2() {
ctx.beginPath();
ctx.arc(circle2.x, circle2.y, circle2.radius, 0, Math.PI * 2);
ctx.fillStyle = circle2.color;
ctx.fill();
}
function update() {
drawCircle();
drawCircle2();
}
function animate() {
ctx.clearRect(0, 0, ctx.width, ctx.height);
requestAnimationFrame(animate);
update();
ctx.flush();
}
animate();
ctx.stroke();
ctx.flush();
};
return (
<GLView style={{ flex: 1 }} onContextCreate={_onGLContextCreate} />
);
}
export { home };
Here is what logs show:
outside 330
inside 330
outside 331
outside 332
outside 333
outside 334
outside 335
outside 336
outside 337
Does anybody know why is being read once in canvas and what could be the solution to increment it as in ouside in canvas function?
I don't know exactly what is the cause, but I found issues in the architecture, and when I fixed them it worked.
TL;DR see result here https://snack.expo.dev/#dozsolti/expogl-ball
You don't need to rerender the component because you update only the canvas so the useState will be swapped with useRef. Also, you probably meant to update the counter every second so for that I changed useTimeout with useInterval. (The useTimeout worked only because it was in a useEffect with the counter dependency which was updated, sort of like calling himself. The correct way was to use a useEffect when the component was loaded and a setInterval)
After that you needed to swap counter with counter.current
Keep in mind that the _onGLContextCreate is running only once so the circle and circle2 objects aren't changing. That's we I changed changed the x value in the update
Besides those, everything looks fine, I guess you optimize the code a little bit, like create a single DrawCircle function that takes x,y as parameters, and so on.
I'm using React Native and Reanimated and I want an animation to play after 2 seconds.
When a user moves a card, the card should stay at it's new position for 2 seconds, and then move back to it's place.
This is what I have:
const panGesture = useAnimatedGestureHandler<PanGestureHandlerGestureEvent>({
onActive: event => {
translateX.value = event.translationX;
if (event.translationX <= 0) {
// disabling swiping from right to left
translateX.value = 0;
}
},
onEnd: event => {
const shouldStick = translateX.value >= TRANSLATE_X_THRESHOULD;
if (shouldStick) {
translateX.value = withTiming(120);
runOnJS(moveBack)(translateX);
} else {
translateX.value = withTiming(0);
}
},
});
I tried using setTimeOut to count 2 seconds, and then update translateX but I get this error:
undefined is not an object (evaluating 'fun.__callAsync')
This is moveBack function:
const moveBack = (translateX: Animated.SharedValue<number>) => {
console.log("TRANSLATEX: " + translateX);
setTimeout(() => {
translateX.value = 0;
}, 2000);
}
I don't even see the TRANSLATEX log, so I guess it won't even get there.
I can't really figure out what's the problem or how to word it so I can find a solution.
The solution was way easier than I thought.
I'm using Reanimated 2.2.0 and there is withDelay option to add to the animation and it works great.
This is what I added after translateX.value = withTiming(120); (instead of the runOnJs line):
translateX.value = withDelay(2000, withTiming(0));
So right after setting translateX to 120, it waits 2 seconds, and then setting the value back to 0.
when using runOnJS
const doSomething = () => {
...
} // declare arrow function before runOnJS
runOnJS(doSomething)(arg)
function doSomething(){
...
} // can declare normal function before/after runOnJS coz of hoisting
I use react-native-reanimated version: '1.7.1' and I tried to process delay between 4 different timing functions.
I tried to find instructions on the web and didn't find one that was clear:
https://docs.swmansion.com/react-native-reanimated/docs/1.x.x/about#reanimated-overview
https://docs.swmansion.com/react-native-reanimated/docs/1.x.x/declarative
I know that in the original reactNative API there is a delay so I tried to find something comparable with this good library
export const createTimingAnimation = (value: Animated.Node<number>, duration = 500, easing = Easing.inOut(Easing.ease), toValue = 1) => {
return Animated.timing(value, {
toValue,
duration,
easing,
});
};
I didn't find any formal way, so I created one:
export const timingAnimationWithDelay = (delay: number, timingAnimation: Animated.BackwardCompatibleWrapper, finishCallback?: any): void => {
setTimeout(() => {
timingAnimation.start(() => {
finishCallback && finishCallback();
});
}, delay);
};
And then you call it like this:
const greetingNfnTiming = createTimingAnimation(animatedValue, 480, Easing.out(Easing.cubic));
timingAnimationWithDelay(1000, greetingNfnTiming, onGreetingFinish);
I'm having an issue upgrading from RxJS5 to version 6. I've got the following code:
private captureEvents(canvasEl: HTMLCanvasElement) {
Observable
.fromEvent(canvasEl, 'mousedown')
.switchMap((e) => {
return Observable
.fromEvent(canvasEl, 'mousemove')
.takeUntil(Observable.fromEvent(canvasEl, 'mouseup'))
.pairwise()
})
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = canvasEl.getBoundingClientRect();
const prevPos = {
x: res[0].clientX - rect.left,
y: res[0].clientY - rect.top
};
const currentPos = {
x: res[1].clientX - rect.left,
y: res[1].clientY - rect.top
};
this.drawOnCanvas(prevPos, currentPos);
});
}
But when I upgrade to RxJS6 I get the following error:
Property 'fromEvent' does not exist on type 'typeof Observable'.
I tried to change my imports from this (RxJS5):
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/takeUntil';
import 'rxjs/add/operator/pairwise';
import 'rxjs/add/operator/switchMap';
To this (RxJS6):
import { Observable, fromEvent } from 'rxjs';
import { switchMap, takeUntil, pairwise } from 'rxjs/operators';
This was my best attempt up upgrading the code:
private captureEvents(canvasEl: HTMLCanvasElement) {
const obsMouseDown = fromEvent(canvasEl, 'mousedown').pipe(
switchMap((e) => {
const obsMouseMove = fromEvent(canvasEl, 'mousemove').pipe(
takeUntil(a => {
const obsMouseUp = fromEvent(canvasEl, 'mouseup').pipe(
pairwise()
);
return obsMouseUp;
}));
return obsMouseMove;
}))
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = canvasEl.getBoundingClientRect();
const prevPos = {
x: res[0].clientX - rect.left,
y: res[0].clientY - rect.top
};
const currentPos = {
x: res[1].clientX - rect.left,
y: res[1].clientY - rect.top
};
this.drawOnCanvas(prevPos, currentPos);
});
}
But this isn't working - I get an error for the "takeUntil" code:
Argument of type '(a: any) => Observable<[Event, Event]>' is not
assignable to parameter of type 'Observable'
plnkr example of original code here:
https://embed.plnkr.co/QSvJxi/
For some reason your plnkr didn't work for me but I'll try my best to provide an answer. I think you should do 2 things here for starter. Try initializing your Observables so it's easier to call them and subscribe to them like so:
const mousedown$ = fromEvent(pauseButton, 'mousedown');
const mouseup$ = fromEvent(resumeButton, 'mouseup');
const mousemove$ = fromEvent(resumeButton, 'mousemove');
The second thing you should pipe your operators now with Rxjs 5 & 6, like so, And subscribe to all your events
mousedown$.pipe(
switchMap(res => {
mousemove$.pipe(//Whatever Operators and subscribitions to other events).subscribe(...)
}),
map(// Whatever you want back from your event)
).subscribe(...)
I refer to you the documentation links switchMap && takeUntil . As many syntaxes are changing in Rxjs don't be shy to brows the documentation, there is nothing better.
fromEvent
Now is already of type Observable. You don't need the chain it to an Observebal instead you can call it directly and affect it to a variable or better a const. Like below:
const source = fromEvent(document, 'click');
as for the import, you figured it right
import { fromEvent } from 'rxjs';
I think you are actually very close, I think you have your pipes too "deep" though - remember you can chain as many operators as you need together in a pipe, so your inner mouse-move-until-mouse-up switchmap should look more like this:
private captureEvents(canvasEl: HTMLCanvasElement) {
const obsMouseDown = fromEvent(canvasEl, 'mousedown').pipe(
switchMap((e) => {
return fromEvent(canvasEl, 'mousemove').pipe(
takeUntil(a => fromEvent(canvasEl, 'mouseup')),
pairwise()
));
}))
.subscribe((res: [MouseEvent, MouseEvent]) => {
// snip
});
}
Main objective : Load animated models exported from Maya into React Native app
Exported files : obj, mtl & png file
I have setup https://github.com/react-community/react-native-webgl in my React Native project and it is working properly.
Now, when I am trying to load the MTL file using the MTLLoader, I am getting following error:
Can't find variable: document
Apparently, the MTLLoader is calling TextureLoader which internally calls some load function which has 'document' reference. So what could be the solution to this ?
Here are the two files that I am using:
three.js
const THREE = require("three");
global.THREE = THREE;
if (!window.addEventListener)
window.addEventListener = () => { };
// require("three/examples/js/renderers/Projector");
require("three/examples/js/loaders/MTLLoader");
require("three/examples/js/loaders/OBJLoader");
export default THREE;
ThreeView.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import { WebGLView } from "react-native-webgl";
import THREE from "./three";
import { image } from "src/res/image";
export default class ThreeView extends Component {
requestId: *;
componentWillUnmount() {
cancelAnimationFrame(this.requestId);
}
onContextCreate = (gl: WebGLRenderingContext) => {
const rngl = gl.getExtension("RN");
const { drawingBufferWidth: width, drawingBufferHeight: height } = gl;
const renderer = new THREE.WebGLRenderer({
canvas: {
width,
height,
style: {},
addEventListener: () => { },
removeEventListener: () => { },
clientHeight: height
},
context: gl
});
renderer.setSize(width, height);
renderer.setClearColor(0xffffff, 1);
let camera, scene;
let cube;
function init() {
camera = new THREE.PerspectiveCamera(75, width / height, 1, 1100);
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load('female-croupier-2013-03-26.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load('female-croupier-2013-03-26.obj', function (object) {
scene.add(object);
}, onLoading, onErrorLoading);
}, onLoading, onErrorLoading);
}
const onLoading = (xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
const onErrorLoading = (error) => {
console.log('An error happened', error);
};
const animate = () => {
this.requestId = requestAnimationFrame(animate);
renderer.render(scene, camera);
// cube.rotation.y += 0.05;
gl.flush();
rngl.endFrame();
};
init();
animate();
};
render() {
return (
<View style={styles.container}>
<WebGLView
style={styles.webglView}
onContextCreate={this.onContextCreate}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
},
webglView: {
width: 300,
height: 300
}
});
This error is as others have said caused by threejs trying to use features from a browser which react-native does not have.
I've gotten so far as to be able to load the textures (which is the stage you're getting the error from) by monkey patching the texture loader to use the loader in react-native-webgl. Add this in your init function (right near the top preferably).
//make sure you have defined renderer and rngl
/*
const renderer = new THREE.WebGLRenderer(...)
const rngl = gl.getExtension("RN");
*/
const loadTexture = async function(url, onLoad, onProgress, onError) {
let textureObject = new THREE.Texture();
console.log("loading",url,'with fancy texture loader');
let properties = renderer.properties.get(textureObject);
var texture = await rngl.loadTexture({yflip: false, image: url});
/*
rngl.loadTexture({ image: url })
.then(({ texture }) => {
*/
console.log("Texture [" + url + "] Loaded!")
texture.needsUpdate = true;
properties.__webglTexture = texture;
properties.__webglInit = true;
console.log(texture);
if (onLoad !== undefined) {
//console.warn('loaded tex', texture);
onLoad(textureObject);
}
//});
return textureObject;
}
THREE.TextureLoader.prototype.load = loadTexture;
This solves the problem of loading textures and I can see them load in Charles but they still don't render on a model so I'm stuck past that point. Technically a correct answer but you'll be stuck as soon as you've implemented it. I'm hoping you can comment back and tell me you've gotten further.
I had a similar setup and encountered same issue. My option was to switch to JSONLoader which doesn’t need document to render in react-native. So, I just loaded my model in Blender with a three-js addon, then exported it as json. Just check out this process of adding a three-js adon to Blender
https://www.youtube.com/watch?v=mqjwgTAGQRY
All the best
this might get you closer:
The GLTF format supports embedding texture images (as base64). If your asset pipeline allows it, you could convert to GLTF and then load into three/react-native.
I had to provide some "window" polyfills for "decodeUriComponent" and "atob" because GLTFLoader uses FileLoader to parse the base64:
I've successfully loaded embedded buffers, but you'll need more polyfills to load textures. TextureLoader uses ImageLoader, which uses document.createElementNS
You are using the MTLLoader which uses TextureLoader, and the TextureLoader uses the ImageLoader.
The imageloader uses the document.createElementNS() function.
what i did to solve this was to directly call the THREEjs TextureLoader:
let texture = new THREE.Texture(
url //URL = a base 64 JPEG string in this case
);
(for the use of Texture check the Texture documentation)
Then i used the Image class from React native (instead of the THREEjs Image, which requires the DOM to be constructed) to give that to the Texture as a property:
import { Image } from 'react-native';
var img = new Image(128, 128);
img.src = url;
texture.normal = img;
And then finally map the texture over the target material:
const mat = new THREE.MeshPhongMaterial();
mat.map = texture;
In the react native documentation it will explain how the react native Image element can be used, it supports base64 encoded JPEG.
Maybe there's a way for you to single out the part where it calls for the TextureLoader and replace that part with this answer. Let me know how it works out.
side note, i havent tried to display this yet in my webGLView, but in the logs it looked like normal threejs objects, it's worth the try
Use TextureLoader from expo-three
import { TextureLoader } from "expo-three";
export function loadTexture(resource) {
if (textureCache[resource]) {
return textureCache[resource].clone();
}
const texture = new TextureLoader().load(resource);
texture.magFilter = NearestFilter;
texture.minFilter = NearestFilter;
textureCache[resource] = texture;
return texture;
}
Source: https://github.com/EvanBacon/Expo-Crossy-Road/blob/master/src/Node/Generic.js