0

I have a class that I want to handle canvas drawing things with. I have a constructor that declares properties like the canvas element and the context, and a drawing function that does the heavy lifting every set number of milliseconds, approximately.

However, none of the instance properties seem to be saved.

// Canvas stuff
class CanvasSingleton {
  constructor() {
    this.cvs = document.getElementById("rush_canvas");
    this.c = this.cvs.getContext("2d");
    this.acc = new Int8Array(64 * 36);
    /* some preparation stuff that's irrelevant to the question */
    this.ani = setInterval(this.aniStep, 100);
    console.log(this.acc);
  }

  aniStep() {
    if (!this.cvs) { throw new Error("Undefined cvs"); }
    if (!this.c) { throw new Error("Undefined c"); }
    if (!this.acc) { throw new Error("Undefined acc"); }
    /* pixel manipulation stuff using the Int8Array */
  }

  end() {
    clearTimeout(this.ani);
  }
}

var r = new CanvasSingleton();

The issue is that none of CanvasSingleton.cvs, CanvasSingleton.c, and CanvasSingleton.acc are defined within CanvasSingleton.aniStep().

I don't know what I'm declaring wrong, because I followed the examples on MDN closely. What am I doing wrong?

haley
  • 845
  • 1
  • 7
  • 15

1 Answers1

0

You didn't mention that you have

<canvas id="rush_canvas">

in your HTML so this is the first thing to verify.

Also, sometimes the Document Object Model (DOM) isn't ready and executing Javascript before DOM is ready often fails to find the element.

To solve this:

 var r;

 window.addEventListener('load', (event) => {
     r = new CanvasSingleton();
 });

Finally...

this.ani = setInterval(this.aniStep, 100);

should be

this.ani = setInterval(this.aniStep.bind(this), 100);

bind(this) makes sure when the interval is fired, the scope of this is the scope of the class and not the scope of setInterval()

John
  • 3,716
  • 2
  • 19
  • 21