小球碰撞(面向对象+canvas+插件封装)

3 篇文章 0 订阅
3 篇文章 0 订阅

一、html代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{
				padding: 0;
				margin: 0;
			}
			#myCan,#myCan2{
				display: block;
				margin: auto;
				border: 4px solid gold;
			}
		</style>
	</head>
	<body>
		<canvas id="myCan" width="600" height="400"></canvas>
	</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="js/crash.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	//	JQ插件化
	$("#myCan").addBall(10).css("border","4px solid red");
	$.eat();
</script>

二、js代码

/*
 * 调用者必须是canvas,JQ对象
 * 
 * 
 */
(function ($){
	var oCan, ctx;
	function Ball(){
		this.r = this.ranNum(20, 50);
		this.maxX = oCan.innerWidth() - this.r;
		this.maxY = oCan.innerHeight() - this.r;
		this.x = this.ranNum(this.r, oCan.innerWidth() - this.r);
		this.y = this.ranNum(this.r, oCan.innerHeight() - this.r);
		//	随机颜色
		this.col = "rgb(" + this.ranNum(0,255) + "," + this.ranNum(0,255) + "," + this.ranNum(0,255) + ")";
		//	随机速度
		this.sx = this.ranNum(2, 5) * (this.ranNum(0, 1) ? 1 : -1);
		this.sy = this.ranNum(2, 5) * (this.ranNum(0, 1) ? 1 : -1);
			
	}
	Ball.prototype = {
		constructor: Ball,
		ranNum: function(x, y){
			return Math.floor(Math.random() * (y-x+1) + x);
		},
		move:function(){
			this.x += this.sx;
			this.y += this.sy;
			if(this.x <= this.r){
				this.x = this.r;
				//	改变方向
				this.sx *= -1;
			}
			//	右边碰壁
			if(this.x >= this.maxX){
				this.x = this.maxX;
				this.sx *= -1;
			}
			if(this.y <= this.r){
				this.y = this.r;
				this.sy *= -1;
			}
			if(this.y >= this.maxY){
				this.y = this.maxY;
				this.sy *= -1;
			}			
		},
		draw:function(){
			ctx.beginPath();
			ctx.arc(this.x, this.y,this.r,0, Math.PI * 2);
			ctx.fillStyle = this.col;
			ctx.fill();	
		}		
	}
	//	给JQ对象拓展方法的一个函数
	/*	$("#div1").css,eg.css
	 * 	拓展使用:$.fn.extend
	 * 	$.isArray()
	 *	 $.extend({
	 * 		eat: function(){
	 * 		
	 * 		}
	 * })
	 */
	$.fn.extend({
		addBall: function(num){
			//	this,就是当前调用该方法的JQ对象
			oCan = this;
			ctx = oCan.get(0).getContext("2d");
			//	存储所有创建的小球
			var aBalls = [];
			for (var i = 0; i < num; i++) {
				aBalls.push(new Ball());	
			}
			var timer = setInterval(function(){
				ctx.clearRect(0, 0, oCan.width(),oCan.height());
				$(aBalls).each(function(){
					this.move();
					this.draw();
				});
			});
			return this;
			console.log(this);
		}
	});
	//	拓展工具方法
	$.extend({
		eat: function(){
			console.log('吃东西');
		}
	});
})(jQuery);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CHH5431

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值