Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursion in typescript gets undefined

I'm using a canvas object inside my component to generate a chart. In order for it animate i'm calling the method recursively. I keep getting an error saying that the method is not defined. Not sure how I need to structure it.

any assistance appreciated.

 // Animate function
protected animate(draw_to) {
// Clear off the canvas
this.ctx.clearRect(0, 0, this.width, this.height);
// Start over
  this.ctx.beginPath();
// arc(x, y, radius, startAngle, endAngle, anticlockwise)
// Re-draw from the very beginning each time so there isn't tiny line spaces between each section (the browser paint rendering will probably be smoother too)
  this.ctx.arc(this.x, this.y, this.radius, this.start, draw_to, false);
// Draw
  this.ctx.stroke();
// Increment percent
  this.curr++;
// Animate until end
  if (this.curr < this.finish + 1) {
    // Recursive repeat this function until the end is reached
    requestAnimationFrame(function () {
      error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
    });
  }
}
like image 802
Jimi Avatar asked Feb 04 '17 20:02

Jimi


1 Answers

You need to use an arrow function to keep the same context in the function you give to requestAnimationFrame.

requestAnimationFrame(() => {
      error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
    });
like image 110
toskv Avatar answered Sep 18 '22 18:09

toskv