以下是JavaScript代码,可以实现动态星空效果:

// 定义画布和绘图上下文
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// 定义星星数组
var stars = [];

// 定义星星类
function Star(x, y, radius, color) {
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.color = color;
  this.vx = Math.random() * 0.3 - 0.15;
  this.vy = Math.random() * 0.3 - 0.15;
}

// 绘制星星
Star.prototype.draw = function() {
  ctx.beginPath();
  ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = this.color;
  ctx.fill();
};

// 更新星星位置
Star.prototype.update = function() {
  this.x += this.vx;
  this.y += this.vy;
  if (this.x < 0 || this.x > canvas.width) {
    this.vx = -this.vx;
  }
  if (this.y < 0 || this.y > canvas.height) {
    this.vy = -this.vy;
  }
};

// 创建星星
function createStars() {
  for (var i = 0; i < 100; i++) {
    var x = Math.random() * canvas.width;
    var y = Math.random() * canvas.height;
    var radius = Math.random() * 2;
    var color = "white";
    stars.push(new Star(x, y, radius, color));
  }
}

// 绘制星空
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < stars.length; i++) {
    stars[i].draw();
    stars[i].update();
  }
  requestAnimationFrame(draw);
}

// 初始化
function init() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  createStars();
  draw();
}

// 监听窗口大小变化
window.addEventListener("resize", function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

// 开始执行
init();

将以上代码保存为一个HTML文件,即可在浏览器中查看动态星空效果。


原文地址: https://www.cveoy.top/t/topic/bwA1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录