JS特效/canvas-绚丽小球

根据网易云课堂的课程,编写的绚丽小球代码,分享一下~

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>绚丽小球</title>
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
	<canvas id="c1" width="600" height="400">
		当前的浏览器不支持该版本!
	</canvas>

<script type="text/javascript" src="js/underscore.js"></script>
<script type="text/javascript" src="js/js.js"></script>
</body>
</html>
body{
	background-color: pink;
}
canvas{
	margin-left: 100px;
	background-color: white;
}
window.onload = function(){
	var oC = document.getElementById('c1');
	var oGC = oC.getContext('2d');

	oC.style.backgroundColor = '#000';

	// 1.小球类
	class Ball{
		/**
		 * 构造器
		 */
		constructor(x, y, color){
			this.x = x;
			this.y = y;
			this.color = color;
			this.r = 26;
		}

		/**
		 * 2.绘制小球
		 */
		render(){
			oGC.save();
			oGC.beginPath();
			oGC.arc(this.x, this.y, this.r, 0, Math.PI*2);
			oGC.fillStyle = this.color;
			oGC.fill();
			oGC.restore();
			// 这里刚开始以为是小球不变小,其实是因为位置没有变。重叠啦
			// alert(this.x);
			// if( this.r < 1 ){
			// 	this.r = 0;
			// }else{
			// 	this.r--;
			// }
			// this.x-=3;
		}
	}

	// 3.会移动的小球类
	class MoveBall extends Ball{
		constructor(x, y, color){
			super(x, y, color);

			// 量的变化
			this.dX = _.random(-5,5);
			this.dY = _.random(-5,5);
			this.dR = _.random(1,3);
		}

		upDate(){
			this.x += this.dX;
			this.y += this.dY;
			this.r -= this.dR;
			if( this.r < 0 ){
				this.r = 0;
			}
		}
	}
	
	// 4.实例化小球
	let ballArr = [];
	let colorArr = ['red', 'green', 'blue', 'yellow', 'purple', 'pink', 'orange', 'skyblue'];

	// 5.监听鼠标的移动
	oC.addEventListener('mousemove', function(e){
		ballArr.push(new MoveBall(e.offsetX, e.offsetY, colorArr[_.random(0,colorArr.length-1)]));
		// console.log(ballArr);
	});

	// 6.开启定时器
	setInterval(function(){
		// 清屏
		oGC.clearRect(0, 0, oC.width, oC.height);


		// 绘制
		for( let i=0; i<ballArr.length; i++ ){
			ballArr[i].render();
			ballArr[i].upDate();
		}

	},50);


}

另外需要下载underscore.js,用到了其中的随机函数,下面是链接

http://www.css88.com/doc/underscore/

欢迎评论一起学习!

猜你喜欢

转载自blog.csdn.net/qq_42381297/article/details/82351067