我对js有点陌生,遇到了一个问题。我试图创建一个天空中的星星动画。我通过在画布上随机创建小圆圈,然后随机选择闪烁的星星(不透明度已更改)来做到这一点。然后我意识到网站在缩放时无法正常工作,所以我决定为窗口大小调整实现一个onevent,当窗口调整大小时,我再次运行相同的函数来重新创建相同的过程,但是在清除所有以前的星星的同时,它们不会成倍增加。这里的问题是,clearRect方法似乎没有为我清除先前绘制的星星。:),任何帮助将不胜感激。这是我的代码。
let starCollection = [];
let randomStars = [];
let numberofStars = 100;
let flickeringStars = 50;
class Star{
constructor(x,y,color,radius){
this._canvas = document.querySelector('canvas');
this._canvas.width = window.innerWidth;
this._canvas.height = window.innerHeight;
this._c = this._canvas.getContext('2d');
this._radius = radius;
this._x = x;
this._y = y;
this._color = color;
}
//drawing individual stars
draw(){
//Drawing
this._c.beginPath();
this._c.arc(this._x,this._y,this._radius,0,Math.PI * 2,false);
this._c.fillStyle = this._color;
this._c.strokeStyle = 'black';
this._c.stroke();
this._c.fill();
this._c.closePath();
}
//Fade in and out for stars
flicker(){
setTimeout(()=>{this._color='#EBEBEB';},300);
setTimeout(()=>{this._color='#D9D9D9';},600);
setTimeout(()=>{this._color='#B6B6B6';},900);
setTimeout(()=>{this._color='#898787';},1200);
setTimeout(()=>{this._color='#4F4F4F';},1500);
setTimeout(()=>{this._color='black';},1800);
setTimeout(()=>{this._color='#4F4F4F';},2100);
setTimeout(()=>{this._color='#898787';},2400);
setTimeout(()=>{this._color='#B6B6B6';},2700);
setTimeout(()=>{this._color='#D9D9D9';},3000);
setTimeout(()=>{this._color='#EBEBEB';},3300);
setTimeout(()=>{this._color='#FFFFFF';},3600);
}
}
海绵宝宝撒
相关分类