Canvas animation / reactjs / with requestAnimationFrame

I have multiple canvas animation on my app, everything is working smooth except this, but now I have a problem with animation Frame (my suspect).

When I load component(animation1) and then change to component(animation 2)and then get back to first component something weird is happened, animation is getting faster every time when I come back to that component and I don't know the reason. Animation for both component is the same, moving objects up and down.

Strange thing is that on my console, moving speed is always the same even after 6-7 switches but objects are moving faster and faster every time... Any idea what may be a problem?

Here is one animation, second is quite similar to this one:

    import React, { Component } from 'react';
let loadBall = [];
let canvas;
let c;
let counterX = 40;
let counterY = 30;
let y =  counterY ;
class Loading extends Component {
    constructor(props){
        super(props)
        this.state = {
            vy: 0,
            time:this.props.time
        }
        this.loadingLoop = this.loadingLoop.bind(this);
    }
    componentDidMount(){
        canvas = document.getElementById('ball');
        canvas.height = 150;
        canvas.width = window.innerHeight;
        c = canvas.getContext('2d');
        this.loadingInit()
        this.loadingLoop()
        window.addEventListener('resize', () => {
            canvas.width = window.innerHeight;
            this.loadingInit()
        })
        this.loadingInit();
    }
    loadingLoop(){
        requestAnimationFrame(this.loadingLoop);
        c.clearRect(0,0, canvas.width, canvas.height);
        for (let i = 0; i < loadBall.length; i++) {
            loadBall[i].update();
        }
    }
    loadingInit(){
        loadBall = [];
        for (let i = 0; i < 3; i++) {
            let radius = 30//Math.floor(Math.random() * 20) + 15;
            let x =  (canvas.width / 2) - (radius * 4) + counterX;
            y = counterY;
            let color = colors[i];
            loadBall.push(new loadingBall(x,y, radius, color));
            counterY += 30;
            counterX += 70;
        }
    }
render() {
    return (
        <canvas id='ball' style={{position:'fixed', top: '50%', left: '50%',WebkitTransform:'translate(-50%, -50%)'}}></canvas>
    );
}
}

function loadingBall(x,y,radius,color){
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
    this.move = 2
    this.update = () =>{
        if (this.y + this.radius + this.move >= canvas.height - 3) {
            this.move = -this.move    
        } 
        if (this.y - this.radius - this.move <= 3) {
            this.move = 2;
        }
        this.y += this.move;
        this.draw();
    }
    this.draw = () => {
        c.beginPath();
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        c.fillRect(this.x, this.y, this.radius, 5);
        c.fillStyle = this.color;
        c.fill();
        c.strokeStyle = this.color;
        c.stroke();
        c.closePath();
    }
}
export default Loading;

Any suggestion can be helpful!

728x90

1 Answers Canvas animation / reactjs / with requestAnimationFrame

This problem is likely caused by your render loop (ie this.loadingLoop) not being stopped after your component is unmounted. As a result, when the component is unmounted the render loop continues to run and, when the component is mounted again, a new render loop is started - this causing two render loops running in tandem, causing the percived "speed up" in animation.

One way to address this would be to add a flag to your component that controls the continuation of the render loop. This could be achieved by adding the following:

constructor(props){
    super(props)
    this.state = {
        vy: 0,
        time:this.props.time
    }
    this.loadingLoop = this.loadingLoop.bind(this);

    // Add this flag to control if animation is allowed to continue
    this.stopAnimation = false;
}

componentDidMount(){

    // Add this to the start of componentDidMount to let animation 
    // start and continue while component is mounted
    this.stopAnimation = false;

    // ...
    // your existing code
    // ...
}

componentWillUnmount() {

    // When the component unmounts, set flag to stop animation
    this.stopAnimation = true;
}

loadingLoop(){

    // If the stopAnimation flag is not truthy, stop future
    // frames for this animation cycle
    if( this.stopAnimation ) {
       return
    }

    requestAnimationFrame(this.loadingLoop);

    c.clearRect(0,0, canvas.width, canvas.height);
    for (let i = 0; i < loadBall.length; i++) {
        loadBall[i].update();
    }
}

4 days ago