0

Im working on a small particle system in html/canvas/javascript. I'm having problems with properties on the canvas getting undefined while running it.

When I test it out I get this error: "Uncaught TypeError: Cannot read property 'clearRect' of undefined". It seems that is is the function "draw()" that causes the error somehow.

Cant figure out why. Any suggestions?

Code:

class Particle {
constructor(x,y,r,d) {
    this.colors = ['#a14b79', '#79a14b', '#4ba19e'];
    this.color = this.colors[Math.floor(Math.random() * 3)];
    this.x = x;
    this.y = y;
    this.r = r;
    this.d = d;
}
}

class Emitter {

constructor(amount) {

    this.amount = amount;
    this.canvas = document.getElementById('c');
    this.context = this.canvas.getContext('2d');
    this.width = window.innerWidth;
    this.height = window.innerHeight;
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.particles = [];
    this.angle = 0;

    this.populate();
}

populate() {

    for(var i = 0; i < this.amount; i++) {
        this.particles.push(new Particle(Math.random()*this.canvas.width,Math.random()*this.canvas.height,Math.random()*15,Math.random()*this.amount));
    }

    setInterval(this.draw,33);
}

draw() {
    this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
    this.context.beginPath();

    for(var i = 0; i < this.particles.length; i++) {
        var p = this.particles[i];
        this.context.moveTo(p.x, p.y);
        this.context.arc(p.x, p.y, p.r, 0, Math.PI*2, true);
        this.context.fillStyle = p.color;
    }
    this.context.fill();
    this.update();
}

update() {
    this.angle += 0.01;
    for(var i = 0; i < this.particles.length; i++) {
        var p = this.particles[i];
        p.y += Math.cos(this.angle+p.d) + 1 + p.r/2;
        p.x += Math.sin(this.angle) * 2;
        if(p.x > this.canvas.width+5 || p.x < -5 || p.y > this.canvas.height) {
            if(i%3 > 0) {
                this.particles[i] = {x: Math.random()*this.canvas.width, y: -10, r: p.r, d: p.d};
            } else {
                if(Math.sin(this.angle) > 0) {
                    this.particles[i] = {x: -5, y: Math.random()*this.canvas.height, r: p.r, d: p.d};
                } else {
                    this.particles[i] = {x: this.canvas.width+5, y: Math.random()*this.canvas.height, r: p.r, d: p.d};
                }
            }
        }
    }
}
}


window.onload = function() {

    const emitter = new Emitter(150);
};
user2952238
  • 749
  • 2
  • 11
  • 36

0 Answers0