声明了JavaScript数组之后,用push方法给这个数组增加内容,运行时报错:
Uncaught TypeError: Cannot set property 'push' of undefined
核心代码:
var hearts=[]; //心的数组
function init (){ //初始化画布的大小
canvas.width = wW;
canvas.height = wH;
for(var i=0; i<num; i++){
hearts.push=new Heart(); //push
}
console.log(new Heart());
requestAnimationFrame(render);
}
如果不用push方法,直接hearts[i] = new Hearts();
报这个错:
全部代码:
<body>
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var wW = window.innerWidth;
var wH = window.innerHeight;
var num = 100; //红心的数量
var heartImage = new Image(); //创建一个新的image对象
heartImage.src = "./heart.svg";
heartImage.onload = render;
init(); //运行初始化函数
var hearts=[]; //心的数组
function init (){ //初始化画布的大小
canvas.width = wW;
canvas.height = wH;
for(var i=0; i<num; i++){
hearts.push=new Heart();
}
console.log(new Heart());
requestAnimationFrame(render);
}
function Heart(){ //构造函数
this.x = Math.random() * wW;
this.y = Math.random() * wH;
this.opacity = Math.random() * .5 + .5;
this.vel = { //位移参数 移动量和方向
x: (Math.random()-.5) * 4,
y: (Math.random()-.5) * 4
};
this.initialW = 470;
this.initialH = 410;
this.initialW*.3;
this.initialH*.3;
this.targetScal = Math.random() * .3 + .02; //最终大小缩放比例
this.scale = this.targetScal * Math.random();
}
Heart.prototype.update = function(){
this.x += this.vel.x;
this.y += this.vel.y;
this.scale += (this.targetScal - this.scale) * .1; //慢慢放大
this.width = this.scale * this.initialW;
this.height = this.scale * this.initialH;
};
Heart.prototype.draw = function(){
ctx.globalAlpha = this.opacity;
ctx.drawImage(heartImage, this.x, this.y, this.width, this.height)
};
var nHeart = new Heart();
function render(){ //渲染函数
ctx.clearRect(0, 0, wW, wH); //清空画布
nHeart.update();
nHeart.draw(); //对象的绘制方法
requestAnimationFrame(render);
}
</script>
</body>
求大佬们解答
函数声明会提升,变量声明可不会提升。
你的代码中,执行init();时变量hearts还没声明。
先声明var hearts = [];
再执行init();
就可以了
另外hearts.push(new Heart());//push是这样用的