简体   繁体   中英

Uncaught TypeError: Type error when calling push()

I'm trying to simulate smoke on canvas . I want to create a new smoke puff and push it in the puffs array but I keep getting the "Uncaught TypeError: Type error" error.
Anyone know what I'm missing?

var puffs = [];

this.tick = function() {
    var puffLength = puffs.length;
    if ( addPuffs && ( puffLength < maxParticles )) {
        puffs.push({ //THIS ONE IT WHAT GIVES ME THE ERROR
            posX: oPoint.x,
            posY: oPoint.y,
            scale: .1,
            age: 0
        });
    }

    for(var i = 0; i < puffLength; i++) {

        var currentPuff = puffs[i];

        if(currentPuff.age == maxLife) {
            puffs.splice(i, 1);
        } else {
            currentPuff.posX += windX,
            currentPuff.posY += windY,
            currentPuff.scale += growingSpeed,
            currentPuff.age++;
        }

    }

    this.render();

}

In the provided fiddle, addPuffs is not defined. You need to define this variable according to your business logic. Also oPoint.x and oPoint.y are not defined, these must also be initialized according to your business logic.

var oPoint = {x:1, y:2}; //declare according to logic
var addPuffs = true; //some logic here
if ( addPuffs && ( puffLength < maxParticles )) {
    puffs.push({ //THIS ONE IT WHAT GIVES ME THE ERROR
        posX: oPoint.x,
        posY: oPoint.y,
        scale: .1,
        age: 0
    });
}

Also when using drawImage() on canvas I believe the first argument must be a DOM element and not a path to the image.

Try:

  var img = new Image();
  img.src = "/static/img/particle.png";
  //Omitted code
  ctx.drawImage(img,80,80,1,1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM