canvas漂浮动画

代码如下:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
	<meta charset="UTF-8">
	<title>canvas漂浮动画</title>
	<style>
	body{
		margin:0px;
	}
	canvas{
		display:block;
	}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>
	<script>
	var canHeight=0;	//画布的宽度
	var canWidth=0;		//画布的长度
	var canvas=null;	//画布对象CanvasRenderingContextD
	var mouseTop=0;		//鼠标的实时纵坐标
	var mouseLeft=0;	//鼠标的实时横坐标
	var bubbleArray=[];	//使用数组储存所有的球球对象

	/*初始化画布,使画布的大小充满整个页面*/
	(function(){
		canHeight=window.innerHeight;
		canWidth=window.innerWidth;
		canvas=document.getElementById("canvas").getContext("2d");
		document.getElementById("canvas").height=canHeight;
		document.getElementById("canvas").width=canWidth;
		canvas.fillStyle="#ff0";
		canvas.fillRect(0,0,canWidth,canHeight);
		canvas.fill();
		window.οnresize=arguments.callee;	/*画布大小随窗口的变化而变化*/
	})();

	/*随机数函数*/
	function random(min,max){
		return Math.floor(Math.random()*max+min);
	}

	/*球的对象,拥有初始化init,绘画draw,移动move方法*/
	function Bubble(){}
	Bubble.prototype={
		"init":function(){
			this.x=random(0,canWidth);
			this.y=random(0,canHeight);
			var colorArray=["#58D3F7","#40FF00","#FFFF00","#FF00FF","#FF4000"];
			this.color=colorArray[random(0,5)];
			this.vx=random(-1,3);
			this.vy=random(-1,3);
			this.r=random(1,5);
			this.prer=this.r;
			this.vr=2;
			this.maxr=50;
		},
		"draw":function(){
			canvas.beginPath();
			canvas.fillStyle=this.color;
			canvas.arc(this.x,this.y,this.r,0,Math.PI*2);
			canvas.fill();
		},
		"move":function(){
			this.x=this.x+this.vx;
			this.y=this.y+this.vy;
			if((this.x<=this.r)||(this.x+this.r>=canWidth)){
				this.vx=-this.vx;
			}
			if((this.y<=this.r)||(this.y+this.r>=canHeight)){
				this.vy=-this.vy;
			}

			/*鼠标66范围内,球球变大;超出66范围,球球变小*/
			var inVertical=Math.abs(this.y-mouseTop);      //垂直
			var inHorizontal=Math.abs(this.x-mouseLeft);    //水平
			if((this.r<this.maxr)&&(inVertical<66)&&(inHorizontal<66)){
				this.r+=this.vr;
			}
			if((this.r>this.prer)&&((inVertical>66)||(inHorizontal>66))){
				this.r-=this.vr;
			}

			this.draw();
		},
	};

	/*创造球球的函数*/
	function create(){
		var bubble=new Bubble();
		bubble.init();
		bubble.draw();
		bubbleArray.push(bubble);
	}

	/*循环生成666个球球*/
	for(var i=0;i<666;i++){
		create();
	}

	/*使用计时器控制球球的动态效果*/
	setInterval(function(){
		canvas.clearRect(0,0,canWidth,canHeight);
		for(var item of bubbleArray){
			item.move();
		}
	},1000/30);

	/*获取鼠标的实时纵横坐标位置*/
	document.body.addEventListener("mousemove",function(e){
		mouseTop=e.clientY;
		mouseLeft=e.clientX;
		console.log(mouseTop+":"+mouseLeft);
	});

	</script>
</body>
</html>
效果图:



知识点:

1, 获取窗口大小   window.innerHeight  window.innerWidth

2, canvas是行内元素,存在行高的问题,要设display:block;

3, clearRect()清除后,需要beginPath(); 否则原来的内容不会清除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值