前端:原生js实现粒子效果

效果截图:
在这里插入图片描述
实现源码:

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		<title>demo</title>			
	</head>
	<body style="overflow:hidden;background:#000">
		<canvas id="container"></canvas>		
		<script>
			var canvas = document.getElementById("container");
			var ctx = container.getContext("2d");
			function resize(){
				canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
				canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;			
			}
			resize();
			window.onresize = resize;
			//创建粒子
			var dots = []
			for(var i=0;i<300;i++){
				var x = Math.random() * canvas.width;
				var y = Math.random() * canvas.height;
				var xa = Math.random() * 2 - 1;
				var ya = Math.random() * 2 - 1;
				dots.push({
					x:x,
					y:y,
					xa:xa,
					ya:ya,
					max:10000
				});
			}
			//创建鼠标点
			var mouse = {x:null,y:null,max:20000};
			window.onmousemove = function(e){
				e = e||window.event;
				mouse.x=e.clientX;
				mouse.y=e.clientY;	
			}
			window.onmouseout = function(){
				mouse.x=null;
				mouse.y=null;	
			}
			function animate(){
				ctx.clearRect(0,0,canvas.width,canvas.height);
				var ndots = [mouse].concat(dots);
				dots.forEach(function(dot){
					dot.x += dot.xa;
					dot.y += dot.ya;
					dot.xa *= (dot.x>canvas.width||dot.x<0) ? -1 : 1;
					dot.ya *= (dot.y>canvas.height||dot.y<0) ? -1 : 1;
					ctx.fillRect(dot.x-0.5,dot.y-0.5,1,1);				
					for(var j=0;j<ndots.length;j++){
						var d2 = ndots[j];
						if(d2 === dot || d2.x === null || d2.y === null)continue;
						var xd = dot.x - d2.x;
						var yd = dot.y - d2.y;
						var dis = xd*xd+yd*yd;
						var dislv;
						if(dis<d2.max){
							if(d2===mouse && dis>(d2.max/2)){
								dot.x -= xd*0.01;
								dot.y -= yd*0.01;
							}
							dislv = (d2.max - dis)/d2.max;
							ctx.beginPath();
							ctx.lineWidth=dislv;
							ctx.strokeStyle = "rgba(255,255,255," + (dislv-0.3) + ")";
							ctx.moveTo(dot.x,dot.y);
							ctx.lineTo(d2.x,d2.y);
							ctx.stroke();
						}
					}
					ndots.splice(ndots.indexOf(dot),1);
				})	
			}
			setInterval(animate,1000/60);
		</script>
	</body>	
</html>


其实只要逻辑清晰,掌握基本的js基础知识就能实现。有不合理的地方希望大家指正。

©️2020 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值