HTML5(Canvas动画)漫游小球


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			canvas{
				border: 1px solid  blue;
			}
		</style>
	</head>
	<body>
		<canvas id="can" width="600px" height="600px"></canvas>
	</body>
	<script type="text/javascript">
		var can = document.getElementById("can");
		var ctx = can.getContext("2d");
		var x = 300;
		var y = 300;
		function Ball(x, y, r, cl, spx){
			this.x = x;
			this.y = y;
			this.r = r;
			this.cl = cl;
			this.spx = spx;
			this.spy = spy;
		}
		Ball.prototype.update = function () {
			this.x += this.spx;	
			this.y += this.spy;
		}
		Ball.prototype.render = function () {
			ctx.beginPath();
			ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
			ctx.fillStyle = this.cl;
			ctx.closePath();
			ctx.fill();
		}
		var objArr = [];
		for(var i = 0; i < 150; i++) {
			var r = (Math.random() * 50 + 5);
			var spx = (Math.random() * 20) - 10;
			var spy = (Math.random() * 20) - 10;
			if(spx == 0 && spy == 0) {
				spx = parseInt(Math.random() * 20) - 10;
				spy = parseInt(Math.random() * 20) - 10;
			}
			var cl = "rgba("+parseInt(Math.random()*256)+"," 
							+parseInt(Math.random() * 256)+","
							+parseInt(Math.random() * 256)+
							"," +(parseInt(Math.random() * 7) + 1) * 0.1+")";
			var ball = new Ball(x, y, r, cl, spx, spy);
			objArr[i] = ball;
		}
		setInterval(function(){
			ctx.clearRect(0, 0, 600, 600);
			for(var i = 0; i < objArr.length; i++){
				objArr[i].update()
				objArr[i].render();
			}
		}, 1000/40);
	</script>
</html>
发布了199 篇原创文章 · 获赞 156 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Harington/article/details/101164008