Points and Lines Animated Background V1.2

by davidxmartins

HTML

<!DOCTYPE html>
  <div id="canvas-container">
    <canvas id="canvas"></canvas>
    <div class="overlay-content">
      <h1>Hello World!</h1>
      <p>This content is on top of the animated background, and it is also centred.</p>
    </div>
  </div>

CSS

body, html {
      margin: 0;
      padding: 0;
      height: 100%;
    }

    #canvas-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      background-color: #000;
      overflow: hidden;
      position: relative;
    }

    #canvas {
      max-width: 100%;
      max-height: 100%;
    }

    .overlay-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white;
      font-size: 24px;
      text-align: center;
      width: 95%;
      font-family: sans-serif;
    }

JavaScript

var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d");

var canvasContainer = document.getElementById("canvas-container");

canvas.width = canvasContainer.offsetWidth;
canvas.height = canvasContainer.offsetHeight;

// Function to resize the canvas when the window is resized
function resizeCanvas() {
  canvas.width = canvasContainer.offsetWidth;
  canvas.height = canvasContainer.offsetHeight;
}

// Push stars to array
var stars = [], // Array that contains the stars
  starCount = 100, // Number of stars
  starRadius = 1.5, // Radius of stars
  lineDistance = calculateLineDistance(); // Maximum distance for lines

for (var i = 0; i < starCount; i++) {
  stars.push({
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    radius: starRadius,
    vx: Math.floor(Math.random() * 50) - 25,
    vy: Math.floor(Math.random() * 50) - 25,
  });
}

// Draw the scene
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.globalCompositeOperation = "lighter";

  for (var i = 0; i < stars.length; i++) {
    var s = stars[i];

    ctx.fillStyle = "white";
    ctx.beginPath();
    ctx.arc(s.x, s.y, s.radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.fillStyle = "white";
    ctx.stroke();
  }

  ctx.beginPath();
  for (var i = 0; i < stars.length; i++) {
    var starI = stars[i];
    ctx.moveTo(starI.x, starI.y);
    for (var j = 0; j < stars.length; j++) {
      var starII = stars[j];
      if (distance(starI, starII) < lineDistance) {
        ctx.lineTo(starII.x, starII.y);
      }
    }
  }
  ctx.lineWidth = 0.05 * starRadius;
  ctx.strokeStyle = "white";
  ctx.stroke();
}

function distance(point1, point2) {
  var xs = point2.x - point1.x;
  xs = xs * xs;

  var ys = point2.y - point1.y;
  ys = ys * ys;

  return Math.sqrt(xs + ys);
}

function calculateLineDistance() {
  // Adjust the line distance based on the canvas size
  var canvasSize = Math.max(canvas.width, canvas.height);
  return canvasSize /...