HTML 星空动态星轨代码 - 创建逼真的星空动画
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Star Trails</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
display: block;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<pre><code><script type="text/javascript">
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight;
var stars = [],
STAR_COUNT = 300,
STAR_RADIUS = 1.5,
STAR_SPEED = 0.5,
STAR_ROTATION_SPEED = 0.001;
for (var i = 0; i < STAR_COUNT; i++) {
stars.push({
x: Math.random() * width,
y: Math.random() * height,
radius: STAR_RADIUS,
rotation: Math.random() * Math.PI * 2,
rotationSpeed: STAR_ROTATION_SPEED,
speed: STAR_SPEED,
color: 'white'
});
}
function render() {
ctx.clearRect(0, 0, width, height);
stars.forEach(function(star) {
ctx.beginPath();
ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
ctx.fillStyle = star.color;
ctx.fill();
star.rotation += star.rotationSpeed;
star.x += Math.cos(star.rotation) * star.speed;
star.y += Math.sin(star.rotation) * star.speed;
if (star.x < -star.radius) {
star.x = width + star.radius;
} else if (star.x > width + star.radius) {
star.x = -star.radius;
}
if (star.y < -star.radius) {
star.y = height + star.radius;
} else if (star.y > height + star.radius) {
star.y = -star.radius;
}
});
requestAnimationFrame(render);
}
render();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/og5d 著作权归作者所有。请勿转载和采集!