一、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);