0

A similar but different issue to a recent post of mine -

I'm experiencing an error "Cannot set property 'globalCompositeOperation' of undefined" when I'm trying to access a class variable from inside a prototype call. Here is the code -

var DrawSlinky = function() {
    this.c = document.getElementById("c"),
    this.w = c.width,
    this.h = c.height,
    this.ctx = c.getContext('2d'),
    
    this.prob = .7,
    this.minSparks = 3,
    this.maxSparks = 10,
    this.minArea = 5,
    this.maxArea = 40,
    this.minVel = 10,
    this.maxVel = 50,

    this.particles = [],
    this.frame = 0;

};

DrawSlinky.prototype.anim = function(){
  this.c.requestAnimationFrame(this.anim);
  
  this.ctx.globalCompositeOperation = 'source-over';
  
  this.ctx.fillStyle = 'rgba(0, 0, 0, .04)';
  this.ctx.shadowBlur = 0;
  this.ctx.fillRect(0, 0, w, h);
  
  this.ctx.globalCompositeOperation = 'lighter';
  
  ++frame;
  
  if(Math.random() < prob) genParticles();
  
  for(var i = 0; i < particles.length; ++i){
    var part = particles[i];
    part.use();
    
    if(part.x < 0 || part.x > w ||
       part.y < 0 || part.y > h ||
       Math.random() < .01){
      particles.splice(i, 1);
      --i;
    }
  }
};

What's going on?

It should be referencing the .ctx in drawSlinky, but i'm getting an infinite loop of errors...

UPDATE - actually, two problems. One is that I can't figure out how to get it to work without hardcoding this.requestAnimationFrame(drawSlinky.anim); (drawSlinky is the instantiation of this DrawSlinky class),

and two, the this.cx.globalCompositeOperation = 'source-over'; isn't referencing the ctx from DrawSlinky and its putting it into an infinite loop.

So I think I need help with both, even though the second problem was what I originally made the question for

realisation
  • 634
  • 6
  • 18

1 Answers1

0
var me = this;
this.c.requestAnimationFrame(function(){
  me.anim();
});

The value of this is set when you call a function, not when you declare it. More info here: https://stackoverflow.com/a/16063711/1641941 under The this variable

Hope that helps

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160