Skip to content

anupamraj176/my-constellation-bg

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

24 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🌌 CosmicCanvas (my-constellation-bg)

The ultimate animated space background library. Create stunning starfields, nebulas, auroras & shooting stars with one line of code. Features 6 built-in themes, click interactions, touch support & zero dependencies!

Version License

✨ Features

  • 🌟 Realistic Star Distribution - 800+ stars with natural brightness distribution and subtle twinkling
  • 🎨 6 Built-in Themes - midnight, aurora, nebula, cosmic, deep-space, warm-galaxy
  • ✨ Aurora Borealis Effect - Stunning northern lights animation with customizable colors
  • πŸ’« Interactive Meteors - Click/tap to spawn shooting stars with varying speeds and colors
  • 🌌 Nebula Clouds - Atmospheric depth with drifting colorful clouds
  • πŸ”„ Parallax Effect - Mouse movement creates 3D depth illusion
  • πŸ“± Touch Support - Full mobile and tablet interaction support
  • ⚑ High Performance - Optimized rendering with configurable performance modes
  • 🎯 Star Clusters - Realistic constellation patterns and grouped formations
  • πŸ’« Bright Star Glow - Special radial glow effects on the brightest stars
  • ⏸️ Pause/Resume - Full animation playback control
  • πŸ“± Responsive - Automatically adapts to canvas/window size
  • ⚑ Lightweight - Pure vanilla JavaScript, zero dependencies
  • 🎯 Easy Integration - Simple API, works with any framework
  • πŸ”§ Backward Compatible - Exports CosmicCanvas, RealisticStarfield, and ConstellationBackground

πŸ†• What's New in v2.1.1

πŸš€ Major Rewrite - CosmicCanvas Engine

  • New Class Name - Now CosmicCanvas (with RealisticStarfield alias for compatibility)
  • 6 Built-in Themes - Pre-configured themes: midnight, aurora, nebula, cosmic, deep-space, warm-galaxy
  • Aurora Borealis - Stunning northern lights effect with wave animations
  • Interactive Meteors - Click/tap anywhere to spawn shooting stars
  • Touch Support - Full mobile and tablet support with touch events
  • Star Clusters - Realistic constellation groupings and formations
  • Performance Modes - Configurable performance levels for different devices
  • Enhanced API - More intuitive configuration and control methods

🎨 Built-in Themes

// Use any built-in theme
const canvas = new CosmicCanvas({
  theme: 'aurora' // midnight, aurora, nebula, cosmic, deep-space, warm-galaxy
});

✨ New Interactive Features

  • Click-to-Spawn - Click anywhere to create meteors
  • Touch Events - Tap on mobile devices
  • Aurora Animation - Flowing northern lights effect
  • Star Clustering - Realistic constellation patterns

Key Options in v2.1.1

Option Type Default Description
theme string 'midnight' Built-in theme: midnight, aurora, nebula, cosmic, deep-space, warm-galaxy
enableInteraction boolean true Enable click/touch to spawn meteors
enableAurora boolean false Enable aurora borealis effect (auto-enabled in aurora theme)
enableClusters boolean true Enable star cluster formations
performanceMode string 'auto' Performance level: 'low', 'medium', 'high', 'auto'
touchSupport boolean true Enable mobile touch events
enableParallax boolean true Enable parallax effect on mouse movement
enableNebula boolean varies Enable nebula clouds (theme-dependent)
starCount number varies Number of stars to render (theme-dependent)

Methods in v2.1.1

// Create with theme
const canvas = new CosmicCanvas({ theme: 'aurora' });

// Control animation
canvas.pause();
canvas.resume();
canvas.togglePause();

// Check state
if (canvas.paused) {
  console.log('Animation is paused');
}

// Get version
console.log(CosmicCanvas.VERSION); // "2.0.0"
console.log(RealisticStarfield.version); // "2.0.0" (alias)

πŸ“¦ Installation

npm install my-constellation-bg

πŸ”§ Build & Test

# Build the package
npm run build

# Test the package (verify it works)
npm test

πŸš€ Usage Guide

Method 1: Vanilla HTML/JavaScript (Easiest)

Option A: Using Built File

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Starfield Background</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            overflow: hidden;
        }

        #starfield-canvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: -1;
        }

        .content {
            position: relative;
            z-index: 1;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            flex-direction: column;
        }

        h1 {
            font-size: 4rem;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <canvas id="starfield-canvas"></canvas>

    <div class="content">
        <h1>Welcome to My Site</h1>
        <p>Beautiful starfield background ✨</p>
    </div>

    <script src="dist/index.js"></script>
    
    <script>
        const canvas = document.getElementById('starfield-canvas');
        
        // Create starfield with theme (recommended)
        const starfield = new CosmicCanvas(canvas, { theme: 'aurora' });

        // OR with custom options:
        // const starfield = new CosmicCanvas(canvas, {
        //     starCount: 1000,              // More stars
        //     backgroundColor: '#0a0a0a',   // Custom background
        //     enableAurora: true,           // Enable aurora effect
        //     enableInteraction: true,      // Click to spawn meteors
        //     performanceMode: 'high',      // Performance level
        //     touchSupport: true,           // Mobile support
        //     parallaxStrength: 0.03,       // Parallax intensity
        //     enableNebula: true,           // Enable nebula clouds
        //     nebulaOpacity: 0.2,           // Nebula visibility
        //     enablePulsate: true           // Pulsating bright stars
        // });

        // Trigger a meteor manually (e.g., on button click)
        // starfield.triggerMeteor();

        // Update options dynamically
        // starfield.setOptions({ meteorInterval: 3000 });

        // Pause/resume controls
        // starfield.pause();
        // starfield.resume();
        // starfield.togglePause();
    </script>
</body>
</html>

Option B: ES6 Module Import

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Same styles as above -->
</head>
<body>
    <canvas id="starfield-canvas"></canvas>
    <div class="content">
        <h1>Welcome</h1>
    </div>

    <script type="module">
        import RealisticStarfield from './src/index.js';
        // OR for backward compatibility:
        // import { ConstellationBackground } from './src/index.js';
        
        const canvas = document.getElementById('starfield-canvas');
        const starfield = new CosmicCanvas(canvas, { theme: 'aurora' });
    </script>
</body>
</html>

Method 2: React

Basic Implementation

import React, { useEffect, useRef } from 'react';
import CosmicCanvas from 'my-constellation-bg';

function App() {
  const canvasRef = useRef(null);
  const starfieldRef = useRef(null);

  useEffect(() => {
    if (canvasRef.current) {
      starfieldRef.current = new CosmicCanvas(canvasRef.current, {
        theme: 'cosmic',
        enableInteraction: true
      });
    }

    return () => {
      if (starfieldRef.current) {
        starfieldRef.current.destroy();
      }
    };
  }, []);

  return (
    <div style={{ position: 'relative', width: '100vw', height: '100vh' }}>
      <canvas
        ref={canvasRef}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: -1
        }}
      />
      
      <div style={{
        position: 'relative',
        zIndex: 1,
        color: 'white',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100vh',
        flexDirection: 'column'
      }}>
        <h1>Welcome to My App</h1>
        <p>Built with React βš›οΈ</p>
      </div>
    </div>
  );
}

export default App;

Reusable Component

// StarfieldCanvas.jsx
import React, { useEffect, useRef } from 'react';
import RealisticStarfield from 'my-constellation-bg';

const StarfieldCanvas = ({ options = {} }) => {
  const canvasRef = useRef(null);
  const starfieldRef = useRef(null);

  useEffect(() => {
    if (canvasRef.current && !starfieldRef.current) {
      starfieldRef.current = new RealisticStarfield(
        canvasRef.current,
        options
      );
    }

    return () => {
      if (starfieldRef.current) {
        starfieldRef.current.destroy();
        starfieldRef.current = null;
      }
    };
  }, [options]);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: -1
      }}
    />
  );
};

export default StarfieldCanvas;

Usage:

import StarfieldCanvas from './StarfieldCanvas';

function App() {
  return (
    <>
      <StarfieldCanvas 
        options={{
          starCount: 1000,
          meteorInterval: 5000
        }}
      />
      <div className="content">
        <h1>Your Content Here</h1>
      </div>
    </>
  );
}

Method 3: Vue 3

Composition API

<template>
  <div class="container">
    <canvas ref="canvasRef" class="starfield-canvas"></canvas>
    <div class="content">
      <h1>Welcome to Vue App</h1>
      <p>Powered by Vue 3 🟒</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import RealisticStarfield from 'my-constellation-bg';

const canvasRef = ref(null);
let starfield = null;

onMounted(() => {
  if (canvasRef.value) {
    starfield = new RealisticStarfield(canvasRef.value, {
      starCount: 800,
      meteorInterval: 8000
    });
  }
});

onBeforeUnmount(() => {
  if (starfield) {
    starfield.destroy();
  }
});
</script>

<style scoped>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.starfield-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.content {
  position: relative;
  z-index: 1;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  flex-direction: column;
}

h1 {
  font-size: 3rem;
  margin-bottom: 1rem;
}
</style>

Options API

<template>
  <div class="container">
    <canvas ref="canvas" class="starfield-canvas"></canvas>
    <div class="content">
      <h1>Your Content</h1>
    </div>
  </div>
</template>

<script>
import RealisticStarfield from 'my-constellation-bg';

export default {
  data() {
    return {
      starfield: null
    };
  },
  mounted() {
    this.starfield = new RealisticStarfield(this.$refs.canvas, {
      starCount: 800,
      meteorInterval: 8000
    });
  },
  beforeUnmount() {
    if (this.starfield) {
      this.starfield.destroy();
    }
  }
};
</script>

<style scoped>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.starfield-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.content {
  position: relative;
  z-index: 1;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  flex-direction: column;
}
</style>

βš™οΈ Configuration Options

Customize the appearance and behavior:

const starfield = new RealisticStarfield(canvas, {
  starCount: 800,                 // Number of stars (scales with screen size)
  backgroundColor: '#000000',     // Pure black deep space
  meteorInterval: 8000,           // Time between meteors (ms)
  meteorAngle: 35,                // Meteor angle in degrees
  enableMeteors: true,            // Enable/disable shooting stars
  enableTwinkle: true,            // Enable/disable star twinkling
  twinkleIntensity: 0.3           // Twinkle strength (0-1)
});

Options Reference

Option Type Default Description
starCount Number 800 Base number of stars (auto-scales with screen size)
backgroundColor String '#000000' Canvas background color (pure black recommended)
meteorInterval Number 8000 Time between meteor spawns (milliseconds)
meteorAngle Number 35 Fixed angle for meteors in degrees (from vertical)
enableMeteors Boolean true Enable or disable shooting stars
enableTwinkle Boolean true Enable or disable star twinkling effect
twinkleIntensity Number 0.3 How much stars twinkle (0 = none, 1 = maximum)

Meteor Speed Distribution

Meteors spawn with varying speeds for a realistic effect:

  • 40% Slow Meteors - Graceful, long trails (speed: 2-3.5)
  • 40% Medium Meteors - Balanced appearance (speed: 4-6)
  • 20% Fast Meteors - Quick bright streaks (speed: 8-12)

Star Brightness Distribution

Stars are distributed with realistic brightness levels:

  • 70% Dim Stars - Tiny, faint (like distant stars)
  • 20% Medium Stars - Moderate brightness
  • 7% Bright Stars - Clearly visible
  • 3% Very Bright Stars - With glow effect

🎨 Styling Examples

Default Realistic Night Sky

// Just use defaults - they look like a real photo!
new RealisticStarfield(canvas);

Dense Starfield

new RealisticStarfield(canvas, {
  starCount: 1500,        // More stars
  meteorInterval: 5000    // More frequent meteors
});

Subtle Background (Less Distracting)

new RealisticStarfield(canvas, {
  starCount: 400,         // Fewer stars
  meteorInterval: 15000,  // Rare meteors
  twinkleIntensity: 0.2   // Very subtle twinkle
});

No Meteors (Static Starfield)

new RealisticStarfield(canvas, {
  enableMeteors: false,   // Disable shooting stars
  enableTwinkle: true     // Keep twinkling
});

🎯 Common Use Cases

Hero Section Background

<style>
    .hero {
        position: relative;
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    #hero-canvas {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
    }
</style>

<section class="hero">
    <canvas id="hero-canvas"></canvas>
    <div class="hero-content">
        <h1>Your Hero Title</h1>
        <p>Subtitle goes here</p>
    </div>
</section>

<script src="dist/index.js"></script>
<script>
    const canvas = document.getElementById('hero-canvas');
    new RealisticStarfield(canvas);
</script>

Full Page Background (with scrollable content)

<style>
    body {
        margin: 0;
        background: #000;
    }
    
    #bg-canvas {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
    }
    
    main {
        position: relative;
        z-index: 1;
        min-height: 100vh;
        color: white;
        padding: 2rem;
    }
</style>

<canvas id="bg-canvas"></canvas>
<main>
    <h1>Page Title</h1>
    <p>Your content scrolls normally while background stays fixed</p>
    <!-- More content... -->
</main>

<script src="dist/index.js"></script>
<script>
    const canvas = document.getElementById('bg-canvas');
    new RealisticStarfield(canvas);
</script>

πŸ› οΈ API Reference

Constructor

new RealisticStarfield(canvas, options)
// OR for backward compatibility:
new ConstellationBackground(canvas, options)

Creates a new starfield instance.

Parameters:

  • canvas (HTMLCanvasElement) - The canvas element to render on
  • options (Object, optional) - Configuration object

Returns: RealisticStarfield instance

Methods

destroy()

Stops the animation and cleans up event listeners. Always call this when removing the canvas (especially in SPAs).

starfield.destroy();

setOptions(options)

Update options dynamically without recreating the instance.

starfield.setOptions({ meteorInterval: 5000 });

triggerMeteor()

Manually trigger a shooting star (e.g., on button click or event).

starfield.triggerMeteor();

resize()

Manually trigger a resize. Usually called automatically on window resize.

starfield.resize();

πŸ“ File Structure

my-constellation-bg/
β”œβ”€β”€ dist/
β”‚   └── index.js          # Built file (after npm run build)
β”œβ”€β”€ src/
β”‚   └── index.js          # Source file (RealisticStarfield class)
β”œβ”€β”€ test.js               # Test suite
β”œβ”€β”€ index.html            # Demo page
β”œβ”€β”€ package.json
└── README.md

πŸ’‘ Best Practices

  1. Z-index: Always set canvas z-index: -1 to keep it behind content
  2. Fixed positioning: Use position: fixed for full-page backgrounds
  3. Performance: Lower starCount for better mobile performance (try 100-150)
  4. Cleanup: Always call destroy() when unmounting (React/Vue components)
  5. Responsive: Canvas automatically resizes, no additional code needed
  6. Build first: Run npm run build before using in production

🌐 Browser Support

Works in all modern browsers that support:

  • Canvas API
  • ES6 Classes
  • RequestAnimationFrame

Tested on: Chrome, Firefox, Safari, Edge


🎯 Real-World Examples

  • Landing page hero sections
  • Login/signup page backgrounds
  • Portfolio websites
  • Dashboard backgrounds
  • Loading screens
  • Presentation slides
  • Marketing pages

οΏ½ Changelog

v2.1.1 (2026-02-01)

Major Rewrite - CosmicCanvas Engine

  • πŸš€ Complete Rewrite: New CosmicCanvas class with enhanced architecture
  • 🎨 6 Built-in Themes: midnight, aurora, nebula, cosmic, deep-space, warm-galaxy
  • ✨ Aurora Borealis: Stunning northern lights animation with wave effects
  • πŸ’« Interactive Meteors: Click/tap anywhere to spawn shooting stars
  • πŸ“± Touch Support: Full mobile and tablet interaction support
  • 🌟 Star Clusters: Realistic constellation patterns and groupings
  • ⚑ Performance Modes: Configurable performance levels (low/medium/high/auto)
  • πŸ”„ Enhanced Parallax: Improved mouse movement depth effects
  • πŸ”§ Backward Compatibility: Maintains RealisticStarfield and ConstellationBackground exports
  • πŸ“ TypeScript Support: Full type definitions included
  • 🏠 Better API: More intuitive configuration and control methods

v1.4.0 (Previous)

Parallax & Nebula Update

  • πŸ”„ Parallax Effect: Mouse movement creates 3D depth illusion
  • 🌌 Nebula Clouds: Optional atmospheric nebula clouds
  • πŸ’« Pulsating Stars: Bright stars gently pulse for realism
  • ⏸️ Pause/Resume: Animation playback control methods
  • πŸ“Š Performance: Smoother rendering and interpolation

v1.2.0 (2026-01-02)

Major Update - Grok-style Improvements

  • ✨ Fixed Position Stars: Stars now have anchor positions with subtle drift movement
  • β˜„οΈ Variable Speed Meteors: Added slow (30%), medium (50%), and fast (20%) meteor types
  • πŸ’« Bright Star Glow: 15% of stars now feature a special radial glow effect
  • 🎨 Enhanced Meteor Colors: Different meteor speeds have unique color schemes
  • βš™οΈ New Options: Added starDrift and driftSpeed configuration options
  • πŸ› Performance: Optimized animation loop for smoother rendering

v1.1.3

  • Bug fixes and stability improvements

v1.1.0

  • Initial public release with blinking stars, connections, and meteors

οΏ½πŸ“„ License

MIT Β© Anupam Raj

🀝 Contributing

Contributions, issues, and feature requests are welcome!

Feel free to check (https://github.com/anupamraj176/my-constellation-bg).

πŸ’– Support

If you like this project, please give it a ⭐ on GitHub!


Made with β˜„οΈ by Anupam Raj

About

A beautiful animated constellation background with blinking stars, dynamic connections, and falling meteors for React, Vue, and vanilla JS

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors