Use requestAnimationFrame in a class
Asked Answered
L

1

16

I'm having problem finding out how I can use requestAnimationFrame in a class.

This code is working fine:

window.onload = function () {
    var width = 20;
    function animation() {
        width++;
        var element = document.getElementById("box");
        element.style.width = width + "px";
        requestAnimationFrame(animation);
    }
    requestAnimationFrame(animation);
};

But when I try putting it into a class, I don't get any result.

class Animation{
    width: number = 20;

    constructor() {
        requestAnimationFrame(this.loop);
    }
    loop() {
        this.width++;
        var element = document.getElementById("box");
        element.style.width = this.width + "px";
        requestAnimationFrame(this.loop);
    }
}
window.onload = function () {
    var animation = new Animation();
};

Could someone tell me what's wrong here?

Labiovelar answered 6/3, 2015 at 22:47 Comment(3)
i would say it is a bad idea to have the requestAnimFrame in the constructor (since a constructor can be called/initialised under various cases), better put it in a method like .initLoop or sth. For the actual question you will have to bind the this.loop method to the "this" object. i.e this.loop.bind(this) so "this" is available and correctly assigned when the loop method will be calledSalaidh
meaning: "requestAnimationFrame(this.loop.bind(this));"Salaidh
@NikosM. I fully agree. I only did it to shorten the example. Didn't knew about bind(this) , I just read up on it, and know it works. =) Thanks!Labiovelar
H
29

requestAnimationFrame(this.loop); If you are passing someone else a function that they are going to call use an arrow i.e requestAnimationFrame(()=>this.loop()); or loop = () => {

More : https://www.youtube.com/watch?v=tvocUcbCupA

Heilner answered 6/3, 2015 at 23:37 Comment(1)
Don't forget about the time argument requestAnimationFrame((t)=>this.loop(t));<br/>Joycelynjoye

© 2022 - 2024 — McMap. All rights reserved.