When I call app.update()
in console this works, but when I use requestAnimationFrame
there is an error:
Uncaught TypeError: Cannot read property 'drops' of undefined at update (oee.html:40)
It works while using setInterval
.
What am I missing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
*{
margin:0;
padding:0;
}
#app{
height:100vh;
width:100vw;
background-color: red;
overflow: hidden;
}
.drop{
position:absolute;
background-color:#fff;
top:10px;
width: 5px;
}
</style>
</head>
<body>
<div id="app">
</div>
<script type="text/javascript">
class App{
constructor(){
this.el = document.getElementById("app");
this.height=this.el.clientHeight;
this.width=this.el.clientWidth;
this.drops=[];
for(var i=0;i<100;i++){
this.drops.push(new Drop(this.height,this.width));
}
}
update(){
this.drops.forEach(function(drop){
drop.update();
});
}
}
class Drop{
constructor(appHeight,appWidth){
this.speed=Math.random();
this.el=document.createElement("div");
this.el.setAttribute("class","drop");
this.el.style.height=(Math.random()*10+5)+"px";
this.el.style.left=(Math.random()*appWidth)+"px";
this.appHeight=appHeight;
document.getElementById("app").appendChild(this.el);
this.el.style.top=0;
}
update(){
this.top=this.el.style.top.replace("px","");
this.el.style.top=(this.top>this.appHeight)?"0px":(parseFloat(this.top) + parseFloat(this.speed*300))+"px";
}
}
var app=new App();
requestAnimationFrame(app.update);
</script>
</body>
</html>