How To Use Requestanimationframe Inside A Class Object
I have a class that takes some coordinate and duration data. I want to use it to animate an svg. In more explicit terms, I want to use that data to change svg attributes over a tim
Solution 1:
You need to bind the requestAnimationFrame
callback function to a context. The canonical way of doing this is like this:
window.requestAnimationFrame(this.step.bind(this))
but it's not ideal because you're repeatedly calling .bind
and creating a new function reference over and over, once per frame.
If you had a locally scoped variable set to this.step.bind(this)
you could pass that and avoid that continual rebinding.
An alternative is this:
functionanimate() {
var start = performance.now();
el = document.querySelector('#start');
// use var self = this if you need to refer to `this` inside `frame()`functionframe(timestamp) {
var progress = timestamp - start;
var currentX = parseInt(el.getAttribute('cx'));
var moveX = distancePerFrame(circleMove.totalFrames(), circleMove.xLine);
el.setAttribute('cx', currentX + moveX);
if (progress < circleMove.duration) {
window.requestAnimationFrame(frame);
}
}
window.requestAnimationFrame(frame);
}
i.e. you're setting up the initial state, and then doing the animation within a purely locally scoped function that's called pseudo-recursively by requestAnimationFrame
.
NB: either version of the code will interact badly if you inadvertently call another function that initiates an animation at the same time.
Post a Comment for "How To Use Requestanimationframe Inside A Class Object"