js前端 实现一个在线网页烟花效果

在这里插入图片描述

随机颜色

var hue = Math.random() * 360;
var hueVariance = 30;

	function setupColors(p){
		p.hue = Math.floor(Math.random() * ((hue + hueVariance) - (hue - hueVariance))) + (hue - hueVariance);
		p.brightness = Math.floor(Math.random() * 21) + 50;
		p.alpha = (Math.floor(Math.random() * 61) + 40) / 100;
	}

随机发射枪口

for (var i = 0; i < count; i++) {
//角度
var angle = 360 / count * i;
//弧度
var radians = angle * Math.PI / 180;

			var p = {};

			p.x = x;
			p.y = y;
			p.radians = radians;
			
			//大小
			p.size = Math.random()*2+1;

			//速度
			p.speed = Math.random()*5+.4;

			//半径
			p.radius = Math.random()*81+50;

			p.fx = x + Math.cos(radians) * p.radius;
			p.fy = y + Math.sin(radians) * p.radius;

			setupColors(p);

			particles.push(p);
		}

每帧更新调用

//requestAnimationFrame
var lastStamp = 0;
function tick(opt=0) {
if(opt-lastStamp>2000){
lastStamp=opt;
createFireworks(Math.random()*canvas.width,Math.random()*canvas.height);
}

	context.globalCompositeOperation = 'destination-out';
	context.fillStyle ='rgba(0,0,0,'+10/100+')';
	context.fillRect(0,0,canvas.width,canvas.height);
	context.globalCompositeOperation = 'lighter';

	drawFireworks();

	requestAnimationFrame(tick);
}
tick();

源码

 javascript:
!(function () {
	var isDebug = false;
	var textCanvas = document.createElement("canvas");
	textCanvas.width=1000;
	textCanvas.height=300;
	if(isDebug){
		textCanvas.style.position="absolute";
		textCanvas.style.zIndex="9999";
		document.body.appendChild(textCanvas);
	}
	var textctx = textCanvas.getContext("2d");
	textctx.fillStyle = "#000000";
	textctx.fillRect(0,0,textCanvas.width,textCanvas.height);

	var canvas = document.createElement("canvas");
	document.body.appendChild(canvas);

	canvas.style.position= "fixed";
	canvas.style.left = "0";
	canvas.style.top = "0";
	canvas.style.zIndex = -1;

	var context = canvas.getContext("2d");

	function resizeCanvas() {
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;

		clearCanvas();
	}

	function clearCanvas() {
		context.fillStyle = "#000000";
		context.fillRect(0, 0, canvas.width, canvas.height);
	}

	resizeCanvas();

	window.addEventListener("resize", resizeCanvas);


	function mouseDownHandler(e) {
		var x = e.clientX;
		var y = e.clientY;
		
		//发射的文字
		createFireworks(x, y,["1024","程序员节日快乐","去死吧 bug!"][Math.floor(Math.random()*3)]);
	}
	document.addEventListener("mousedown", mouseDownHandler);

	var particles = [];

	function createFireworks(x, y,text="") {

		var hue = Math.random() * 360;
		var hueVariance = 30;

		function setupColors(p){
			p.hue = Math.floor(Math.random() * ((hue + hueVariance) - (hue - hueVariance))) + (hue - hueVariance);
			p.brightness = Math.floor(Math.random() * 21) + 50;
			p.alpha = (Math.floor(Math.random() * 61) + 40) / 100;
		}

		if(text!=""){
			
			var gap = 6;
			var fontSize = 120;

			textctx.font=fontSize+"px _sans";
			textctx.fillStyle = "#ffffff";
			
			var textWidth = Math.ceil(textctx.measureText(text).width);
			var textHeight = Math.ceil(fontSize*1.2);

			textctx.fillText(text,0,fontSize);
			var imgData = textctx.getImageData(0,0,textWidth,textHeight);

			if(isDebug)context.putImageData(imgData,400,300)
			
			textctx.fillStyle = "#000000";
			textctx.fillRect(0,0,textCanvas.width,textCanvas.height);

			for (var h = 0; h < textHeight; h+=gap) {
			    for(var w = 0; w < textWidth; w+=gap){
			            var position = (textWidth * h + w) * 4;
			            var r = imgData.data[position], g = imgData.data[position + 1], b = imgData.data[position + 2], a = imgData.data[position + 3];
			    
			    		if(r+g+b==0)continue;

			            var p = {};

						p.x = x;
						p.y = y;

						p.fx = x + w - textWidth/2;
						p.fy = y + h - textHeight/2;

						p.size = Math.floor(Math.random()*2)+1;
						p.speed = 1;

						setupColors(p);

						particles.push(p);
			    }
			}
		}else{
			var count = 100;
			for (var i = 0; i < count; i++) {
				//角度
				var angle = 360 / count * i;
				//弧度
				var radians = angle * Math.PI / 180;

				var p = {};

				p.x = x;
				p.y = y;
				p.radians = radians;
				
				//大小
				p.size = Math.random()*2+1;

				//速度
				p.speed = Math.random()*5+.4;

				//半径
				p.radius = Math.random()*81+50;

				p.fx = x + Math.cos(radians) * p.radius;
				p.fy = y + Math.sin(radians) * p.radius;

				setupColors(p);

				particles.push(p);
			}
		}
	}
	function drawFireworks() {
		clearCanvas();

		for (var i = 0; i < particles.length; i++) {
			var p = particles[i];

			p.x += (p.fx - p.x)/10;
			p.y += (p.fy - p.y)/10-(p.alpha-1)*p.speed;

			p.alpha -= 0.006;

			if (p.alpha<=0) {
				particles.splice(i, 1);
				continue;
			}

			context.beginPath();
			context.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
			context.closePath();

			context.fillStyle = 'hsla('+p.hue+',100%,'+p.brightness+'%,'+p.alpha+')';
			context.fill();
		}
	}

	//requestAnimationFrame
	var lastStamp = 0;
	function tick(opt=0) {
		if(opt-lastStamp>2000){
			lastStamp=opt;
			createFireworks(Math.random()*canvas.width,Math.random()*canvas.height);
		}

		context.globalCompositeOperation = 'destination-out';
		context.fillStyle ='rgba(0,0,0,'+10/100+')';
		context.fillRect(0,0,canvas.width,canvas.height);
		context.globalCompositeOperation = 'lighter';

		drawFireworks();

		requestAnimationFrame(tick);
	}
	tick();
})();

背景音乐自动播放

audio id="bgmusic" src="./bgm.mp3" autoplay="autoplay" loop="loop" style="display: block; width: 3%; height:3%;"></audio>
        <script type="text/javascript">
      function toggleSound() {
                var music = document.getElementById("bgmusic");//获取ID
                    console.log(music);
                    console.log(music.paused);
                if (music.paused) { //判读是否播放
                    music.paused=false;
                    music.play(); //没有就播放
                }
    
            }
            setInterval("toggleSound()",1);
    </script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
烟花绽放效果是一种非常美丽的视觉效果,可以通过前端的CSS和JavaScript来实现。下面是一个简单的实现方法: 1. HTML结构 首先,我们需要在HTML中定义一个容器,用来显示烟花效果。在这个容器中,我们将创建一个`<canvas>`元素,并设置它的宽度和高度。 ```html <div id="firework-container"> <canvas id="firework-canvas" width="800" height="600"></canvas> </div> ``` 2. CSS样式 接下来,我们需要设置一些CSS样式,将容器居中,并将背景色设置为黑色。 ```css #firework-container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: black; } ``` 3. JavaScript代码 最后,我们需要使用JavaScript来实现烟花绽放效果。具体实现方法如下: ```javascript // 获取canvas元素和上下文对象 var canvas = document.getElementById("firework-canvas"); var ctx = canvas.getContext("2d"); // 定义烟花粒子的数量 var numParticles = 100; // 定义烟花粒子的数组 var particles = []; // 定义烟花的颜色 var colors = ["red", "green", "blue", "yellow", "purple"]; // 定义烟花的初始位置 var originX = canvas.width / 2; var originY = canvas.height; // 定义烟花的半径 var radius = 5; // 创建烟花粒子 for (var i = 0; i < numParticles; i++) { particles.push({ x: originX, y: originY, color: colors[Math.floor(Math.random() * colors.length)], speed: Math.random() * 5 + 1, angle: Math.random() * Math.PI * 2 }); } // 定义动画函数 function animate() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 循环遍历烟花粒子 particles.forEach(function(particle) { // 更新粒子位置 particle.x += Math.cos(particle.angle) * particle.speed; particle.y += Math.sin(particle.angle) * particle.speed; // 绘制粒子 ctx.beginPath(); ctx.arc(particle.x, particle.y, radius, 0, Math.PI * 2); ctx.fillStyle = particle.color; ctx.fill(); }); // 如果粒子已经越过画布边界,则重新生成新的烟花 if (particles[0].y < 0) { particles = []; for (var i = 0; i < numParticles; i++) { particles.push({ x: originX, y: originY, color: colors[Math.floor(Math.random() * colors.length)], speed: Math.random() * 5 + 1, angle: Math.random() * Math.PI * 2 }); } } // 循环执行动画函数 requestAnimationFrame(animate); } // 开始执行动画函数 animate(); ``` 上面的代码中,我们首先获取了`<canvas>`元素和上下文对象,并定义了烟花粒子的数量、颜色、初始位置和半径。接着,我们使用`for`循环来创建烟花粒子,并将它们存储在一个数组中。 在动画函数中,我们先清空画布,然后循环遍历烟花粒子,更新它们的位置并绘制到画布上。如果粒子已经越过画布的上边界,则重新生成新的烟花。 最后,我们使用`requestAnimationFrame()`函数来循环执行动画函数,实现烟花绽放的效果。 希望这个简单的例子能够帮助您理解如何使用前端的CSS和JavaScript来实现烟花绽放效果

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

极客柒

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

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

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

打赏作者

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

抵扣说明:

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

余额充值