canvas背景

一、普通的星星

//创建一个星星对象
class Star {
  constructor() {
    this.x = windowWidth * Math.random(); //横坐标
    this.y = 5000 * Math.random(); //纵坐标
    this.text = "."; //文本
    this.color = "white"; //颜色
  }
  //初始化
  init() {
    this.getColor();
  }
  //绘制
  draw() {
    context.fillStyle = this.color;
    context.fillText(this.text, this.x, this.y);
  }
}

//画星星
for (let i = 0; i < starCount; i++) {
  let star = new Star();
  star.init();
  star.draw();
  arr.push(star);
}

canvas背景_第1张图片

二、闪动的星星  

//创建一个星星对象
class Star {
  constructor() {
    this.x = windowWidth * Math.random(); //横坐标
    this.y = 5000 * Math.random(); //纵坐标
    this.text = "."; //文本
    this.color = "white"; //颜色
  }
	// 获取随机颜色
  getColor() {
    let _r = Math.random();
    if (_r < 0.5) {
      this.color = "#333";
    } else {
      this.color = "white";
    }
  }

  //初始化
  init() {
    this.getColor();
  }
  //绘制
  draw() {
    context.fillStyle = this.color;
    context.fillText(this.text, this.x, this.y);
  }
}

//画星星
for (let i = 0; i < starCount; i++) {
  let star = new Star();
  star.init();
  star.draw();
  arr.push(star);
}

//繁星闪起来
let t1
function playStars() {
  for (let n = 0; n < starCount; n++) {
    arr[n].getColor();
    arr[n].draw();
  }
  t1 = requestAnimationFrame(playStars);
}

你可能感兴趣的:(前端,javascript,python)