canvas画布漂浮动画

直接上代码,简单

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>CanvasLove</title>
		<style>
			#canvas{
				background-color: #000000;
			}
		</style>
	</head>
	<body>
		<canvas id="canvas" ></canvas>
	</body>
	<script>
		var canvas = document.getElementById('canvas') ;
		var ctx = canvas.getContext('2d') ;
		 
		var w = window.innerWidth;
		var h = window.innerHeight;
		canvas.width=w;
		canvas.height=h;	
		
		//创建小球对象
		var aBubble=[]; //存放生成的球对象
		function Bubble(){};
		Bubble.prototype={
			init:function(){
				this.x=random(0,w);
				this.y=random(0,h);
				this.vX=random(-1,1);
				this.vY=random(-1,1);
				this.color="rgb("+Math.random()*255+","+Math.random()*255+","+Math.random()*255+")";				
				this.r=random(2,8);
			},
			draw:function(){
				ctx.beginPath();
				ctx.fillStyle=this.color;
				ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
				ctx.fill();
			},
			move:function(){
				this.x+=this.vX;
				this.y+=this.vY;
				if(this.x-this.r<0 || this.x+this.r>w){
					this.vX=-this.vX;
					this.vY=-this.vY;
				}
				if(this.y-this.r<0 || this.y+this.r>h){
					this.vX=-this.vX;
					this.vY=-this.vY;
				}
				this.draw();
			}
		}
		
					 
		function random(min,max){
			return Math.random()*(max-min)+min;
		}
		
		
		function createBubble(num){
			for(var i=0;i<num;i++){
				var bubble=new Bubble();
				bubble.init();
				bubble.draw();
				aBubble.push(bubble);
			}
		}
		
		createBubble(520);
		
		setInterval(function(){
			ctx.clearRect(0,0,w,h);
			for(var item of aBubble){
				item.move();
			}
		},1000/60);
	</script>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值