Jump to content

looping with requestAnimationFrame, loses scope after a single loop


cnwerb
 Share

Recommended Posts

I'm trying to start a game loop in my PixiJS app but I'm getting an annoying error, the function loses scope after the first loop. Here's my code to make it clear: (take note of the console.log statements)

import { Component, OnInit } from '@angular/core';
declare var PIXI: any;
declare var $: any;

@Component({
  selector: 'pixi-component',
  templateUrl: './pixi.component.html',
  styleUrls: ['./pixi.component.css']
})
export class PixiComponent implements OnInit {

    private renderer;
    private stage;

    constructor() {}

    ngOnInit() {
        this.generatePixiCanvas();
    }


    generatePixiCanvas() {
        this.create(this.getParentDivWidth(), this.getParentDivHeight());
        this.stage = new PIXI.Container();
        this.loop.bind(this);
        this.loop();
        this.renderer.render(this.stage);
    }

    getParentDivHeight() {
        return $('#canvas').height();
    }

    getParentDivWidth() {
        return $('#canvas').width();
    }

    create(width: number, height: number, scale: boolean = false){
        if (this.renderer) return this;

        this.renderer = PIXI.autoDetectRenderer(this.width, this.height);
        document.getElementById('pixi-canvas-container').appendChild(this.renderer.view);

        console.log("we got here");
        return this;
    }

    loop = function(){
        requestAnimationFrame(this.loop);
        console.log("loop");
    }
}

 

So when I run this code, I get the following output on the browser console:

"we got here"

"loop"

"EXCEPTION: Cannot read loop property of undefined"

 

So it seems to me that the "this" object is losing scope after the first call of the loop() function. How can I keep the scope? You can see I tried this.loop.bind(this) but it doesn't work 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...