canvas particle effects

Underscore.js framework uses
the mouse to move the event
to generate and change the position of the ball through the class
to add the ball to clear the screen by a timer

<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<script src='js/underscore.js'></script>

	<style>
		.canvas{
			border:solid 2px black;
			background-color: black;
		}
	
	
	</style>
</head>
<body>

	<canvas width="1390px" height="700px" class='canvas'>您的浏览器不支持canvas标签,请变更支持canvas的浏览器</canvas>
	<script>
			var	canvas=document.querySelector(".canvas");
			var bi=canvas.getContext('2d');
			var ballArr=[]; //小球数组

			//小球类
				function Ball(x,y)
				{
					this.x=x;
					this.y=y;
					this.r=_.random(5,10);
					this.color=_.sample(['red','orange','yellow','green','cyan','blue','purple']);
					//坐标的增减量
					this.dx=_.random(-4,4);
					this.dy=_.random(-4,4);

					//每有一个小球就放进数组里,为后面多个小球同时操作铺垫
					ballArr.push(this);
				}
				//给所有对象提供共有的画小球原型方法
				Ball.prototype.draw=function()
				{
					//如果小球半径减小到0,就消失不生成
					if(this.r<=0)
					{
						return;
					}
					//画小球
					bi.beginPath();
					bi.arc(this.x,this.y,this.r,0*Math.PI,2*Math.PI,false);
					bi.fillStyle=this.color;
					bi.fill();

					bi.closePath();
				}
				//使鼠标移动时小球位置也改变
				Ball.prototype.update=function()
				{
					this.x+=this.dx;
					this.y+=this.dy;
					this.r-=0.5;
					//如果当前小球半径小于0,则移除
					if(this.r<=0)
					{
						_.without(ballArr,this);
					}
				}
			//鼠标移动时间创建小球
			
			canvas.onmousemove=function(){
				new Ball(event.offsetX,event.offsetY);
			};
			//fps=50;
			setInterval(function(){
				//清屏
				bi.clearRect(0,0,1390,700);
				//划上所有的小球
				_.each(ballArr,function(ele){
					//使鼠标停住时改变小球位置
					ele.update();
					ele.draw();

				})
			},25);

	</script>
	
</body>

</html>
Published 281 original articles · won praise 3 · Views 4826

Guess you like

Origin blog.csdn.net/weixin_43294560/article/details/103995701