<!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>&lt;script type=&quot;text/javascript&quot;&gt;
	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 &lt; 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 &lt; -star.radius) {
				star.x = width + star.radius;
			} else if (star.x &gt; width + star.radius) {
				star.x = -star.radius;
			}

			if (star.y &lt; -star.radius) {
				star.y = height + star.radius;
			} else if (star.y &gt; height + star.radius) {
				star.y = -star.radius;
			}
		});

		requestAnimationFrame(render);
	}

	render();
&lt;/script&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/og5d 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录