星空背景源码动态

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Html+js 实现星空背景</title>

<style>

canvas {
position: fixed; /* 设置定位 */
top: 0;
left: 0;
z-index: -1; /* 使画布基于最低层 */
background: #0e1729; /* 画布背景色 */
}
</style>


</head>
<body>
<!-- 创建画布 -->
<canvas id="starfield"></canvas>
</body>

<script>
    var canvas;
var stars_count;
var stars;
ini();
makeStars();
var interval = setInterval(function() { drawStars(); }, 50); // 定时刷新星星数据

function ini() { // 初始化
canvas = document.getElementById("starfield");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext("2d");
stars = Array(); // 数组存放随机生成的星星数据(x, y, 大小,颜色,速度)
stars_count = 300; // 星星数量
clearInterval(interval);
}

function makeStars() { // 随机生成星星数据
for (var i = 0; i < stars_count; i++) {
let x = Math.random() * canvas.offsetWidth;
let y = Math.random() * canvas.offsetHeight;
let radius = Math.random() * 0.8;
let color = "rgba(" + Math.random() * 255 + "," + Math.random() * 255 + "," + Math.random() * 255 + ",0.8)";
let speed = Math.random() * 0.5;
let arr = { 'x': x, 'y': y, 'radius': radius, 'color': color, 'speed': speed }; // (x, y, 大小,颜色,速度)
stars.push(arr); // 随机生成的星星数据存在这里
}
}

function drawStars() { // 把星星画到画布上
context.fillStyle = "#0e1729";
context.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < stars.length; i++) {
var x = stars[i]['x'] - stars[i]['speed'];
if (x < -2 * stars[i]['radius']) x = canvas.width;
stars[i]['x'] = x;
var y = stars[i]['y'];
var radius = stars[i]['radius'];
context.beginPath();
context.arc(x, y, radius * 2, 0, 2 * Math.PI);
context.fillStyle = "rgba(" + Math.random() * 255 + "," + Math.random() * 255 + "," + Math.random() * 255 + ",0.8)";
context.fill();
}
}

window.onresize = function() { // 窗口大小发生变化时重新随机生成星星数据
ini();
makeStars();
interval = setInterval(function() { drawStars(); }, 50);
}
</script>


</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄大新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值