用HTML5 Canvas和JavaScript联手打造生动的动态星空背景效果 - 从代码实现开始
最编程
2024-02-16 15:10:29
...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>星空背景</title>
</head>
<body style="overflow-x:hidden;">
<canvas id="canvas"></canvas> <!-- 创建一个画布元素 -->
</body>
<script>
// 获取画布元素和2D上下文
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// 设置画布宽度和高度
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight-50;
hue = 217; // 设定颜色
stars = []; // 存储星星的数组
count = 0,
maxStars = 1500; // 星星数量
// 创建用于渲染星星的小画布
canvas2 = document.createElement('canvas');
w2 = canvas2.width = 100;
h2 = canvas2.height = 100;
ctx2 = canvas2.getContext("2d");
gradientCache = ctx2.createRadialGradient(w2 / 2, h2 / 2, 0, w2 / 2, h2 / 2, w2 / 2);
gradientCache.addColorStop(0.025, '#fff');
gradientCache.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
gradientCache.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
gradientCache.addColorStop(1, 'transparent');
ctx2.fillStyle = gradientCache;
ctx2.beginPath();
ctx2.arc(w2 / 2, h2 / 2, w2 / 2, 0, Math.PI * 2);
ctx2.fill();
// 生成随机数
function random(min, max) {
if (arguments.length < 2) {
max = min;
min = 0;
}
if (min > max) {
var hold = max;
max = min;
min = hold;
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 确定星星轨道半径
function maxOrbit(x, y) {
var max = Math.max(x, y), diameter = Math.round(Math.sqrt(max * max + max * max));
return diameter / 2;
}
// 构造函数用于创建星星对象
Star = function() {
this.orbitRadius = random(maxOrbit(w, h));
this.radius = random(60, this.orbitRadius) / 10;
this.orbitX = w / 2;
this.orbitY = h / 2;
this.timePassed = random(2, maxStars);
this.speed = random(this.orbitRadius) / 120000;
this.alpha = random(2, 10) / 10;
count++;
stars[count] = this;
}
// 在画布上绘制星星
Star.prototype.draw = function() {
x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX;
y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY;
twinkle = random(10);
if (twinkle === 1 && this.alpha > 0) {
this.alpha -= 0.05;
} else if (twinkle === 2 && this.alpha < 1) {
this.alpha += 0.05;
}
ctx.globalAlpha = this.alpha;
ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
this.timePassed += this.speed;
}
// 创建一定数量的星星对象
for (var i = 0; i < maxStars; i++) {
new Star();
}
// 开始绘制星空背景
function start() {
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = 1;
ctx.fillStyle = 'hsla(' + hue + ', 64%,6%,0.2)';
ctx.fillRect(0, 0, w, h)
ctx.globalCompositeOperation = 'lighter';
for (var i = 1, l = stars.length; i < l; i++) {
stars[i].draw();
};
window.requestAnimationFrame(start);
}
start(); // 调用开始函数
</script>
</html>
下一篇: 回溯20年:一起见证腾讯QQ的界面演变史