Points and Lines Animated Background V1.3
by davidxmartins
June 28, 2023
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: #007767;
overflow: hidden;
position: relative;
}
#canvas {
max-width: 100%;
max-height: 100%;
}
.overlay-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
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;
var stars = [],
starCount = 100,
starRadius = 1.5,
lineDistance = calculateLineDistance();
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,
});
}
function resizeCanvas() {
canvas.width = canvasContainer.offsetWidth;
canvas.height = canvasContainer.offsetHeight;
}
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();
}
}
function drawLines() {
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.04 * 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() {
var diagonal = Math.sqrt(
canvas.width * canvas.width + canvas.height * canvas.height
);
return diagonal / 6; // Adjust this value as needed for line density
}
function update() {
for (var i = 0; i < stars.length; i++) {
var s = stars[i];
s.x += s.vx / 60;
s.y += s.vy / 60;
if (s.x < 0...