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 + 150;
    this.color = this.getRandomColor();
    this.points = this.generatePoints();
    this.angle = 0;
    this.rotationSpeed = (Math.random() - 0.5) * 0.001;
  }

  getRandomColor() {
    const colors = [
    "rgba(65, 105, 225, 0.1)", // Royal Blue
    "rgba(138, 43, 226, 0.1)", // Blue Violet
    "rgba(255, 20, 147, 0.1)", // Deep Pink
    "rgba(75, 0, 130, 0.1)", // Indigo
    "rgba(147, 112, 219, 0.1)", // Medium Purple
    "rgba(218, 112, 214, 0.1)" // Orchid
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }

  generatePoints() {
    const numberOfPoints = 12;
    const angleStep = Math.PI * 2 / numberOfPoints;
    cons.........完整代码请登录后点击上方下载按钮下载查看

网友评论0