canvas实现浩瀚星空效果代码

代码语言:html

所属分类:其他

代码描述:canvas实现浩瀚星空效果代码

代码标签: canvas 浩瀚 星空

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
<style>
body,
html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

canvas {
  display: block;
  background-color: #000000;
}
</style>


  
  
</head>

<body translate="no">
  <canvas id="nebulaCanvas"></canvas>
  
      <script>
const canvas = document.getElementById("nebulaCanvas");
const ctx = canvas.getContext("2d");

let width, height;
let nebulaClouds = [];
let stars = [];

class Star {
  constructor() {
    this.reset();
  }

  reset() {
    this.x = Math.random() * width;
    this.y = Math.random() * height;
    this.size = Math.random() * 2 + 0.5;
    this.speed = Math.random() * 0.05 + 0.01;
    this.brightness = Math.random();
  }

  update() {
    this.y -= this.speed;
    if (this.y < 0) {
      this.reset();
      this.y = height;
    }
    this.brightness = Math.sin(Date.now() * this.speed * 0.01) * 0.5 + 0.5;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 255, 255, ${this.brightness})`;
    ctx.fill();
  }}


class NebulaCloud {
  constructor() {
    this.reset();
  }

  reset() {
    this.x = Math.random() * width;
    this.y = Math.random() * height;
    this.radius = Math.random() * 300 +.........完整代码请登录后点击上方下载按钮下载查看

网友评论0