动态放烟花的前端网页代码

使用JavaScript实现的动态放烟花的前端网页代码,请按照要求复制到HTML文件中:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>动态放烟花</title>
	<style>
		body {
			margin: 0;
			padding: 0;
		}
		canvas {
			display: block;
			position: absolute;
			top: 0;
			left: 0;
			z-index: -1;
		}
	</style>
</head>
<body>
	<canvas id="myCanvas"></canvas>
	<script>
        // 获取canvas元素和上下文
		var canvas = document.getElementById("myCanvas");
		var ctx = canvas.getContext("2d");

        // 设置canvas大小和背景颜色
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
		ctx.fillStyle = "#000";
		ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 创建烟花类
		function Firework() {
			this.x = Math.random() * canvas.width; // 烟花的x坐标
			this.y = canvas.height; // 烟花的y坐标
			this.color = `hsl(${Math.floor(Math.random() * 360)}, 100%, 50%)`; // 烟花颜色
			this.radius = 2; // 烟花半径
			this.velocity = { // 烟花速度
				x: Math.random() * 6 - 3,
				y: Math.random() * -15 - 10
			};
			this.gravity = 0.2; // 烟花重力
			this.opacity = 1; // 烟花透明度
			this.trail = []; // 烟花粒子轨迹
		}

        // 更新烟花位置
		Firework.prototype.update = function() {
			this.x += this.velocity.x;
			this.velocity.y += this.gravity;
			this.y += this.velocity.y;
			this.opacity -= 0.02;
			
            // 更新烟花粒子轨迹
			this.trail.push({x: this.x, y: this.y});

            // 删除不需要的烟花粒子
			if (this.trail.length > 15) {
				this.trail.shift();
			}
		}

        // 绘制烟花
		Firework.prototype.draw = function() {
			ctx.globalAlpha = this.opacity;
			ctx.beginPath();
			ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
			ctx.fillStyle = this.color;
			ctx.fill();

            // 绘制烟花粒子轨迹
			for (var i = 0; i < this.trail.length; i++) {
				ctx.fillStyle = this.color;
				ctx.fillRect(this.trail[i].x, this.trail[i].y, this.radius, this.radius);
			}
		}

        // 创建烟花数组
		var fireworks = [];

        // 循环绘制烟花
		function loop() {
			setTimeout(function() {
				requestAnimationFrame(loop);
				ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
				ctx.fillRect(0, 0, canvas.width, canvas.height);

                // 随机生成烟花
				if (Math.random() < 0.03) {
					fireworks.push(new Firework());
				}

                // 更新和绘制每个烟花
				for (var i = 0; i < fireworks.length; i++) {
					fireworks[i].update();
					fireworks[i].draw();
					
                    // 删除已经消失的烟花
					if (fireworks[i].opacity <= 0) {
						fireworks.splice(i, 1);
					}
				}
			}, 1000 / 60);
		}

		loop();
	</script>
</body>
</html>

说明:

  • 该代码使用Canvas绘制烟花动画效果。
  • 程序会不断随机生成烟花,并对每个烟花进行位置、速度等更新,同时也记录下烟花生成时的位置,形成烟花粒子轨迹。
  • 使用循环不断对所有烟花进行更新和绘制,同时删除已经消失的烟花。
  • 烟花的数量、颜色、速度等都是随机生成的,使得每次运行效果不同

效果图:

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值