未捕获的类型错误:调用 push() 时的类型错误

Uncaught TypeError: Type error when calling push()

本文关键字:类型 错误 push 调用      更新时间:2023-09-26

我正在尝试模拟canvas上的烟雾。我想创建一个新的烟扑并将其推入烟扑数组中,但我不断收到"Uncaught TypeError: Type error"错误。
有人知道我错过了什么吗?

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();
}

在提供的小提琴中,未定义addPuffs。 您需要根据业务逻辑定义此变量。 此外,oPoint.xoPoint.y也没有定义,还必须根据业务逻辑初始化这些内容。

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
    });
}

此外,当canvas上使用drawImage()时,我相信第一个参数必须是DOM元素,而不是图像的路径。

尝试:

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