html部分
<canvas id="canvas" width="1000" height="800"></canvas>
引入<script src="lib/underscore-min.js"></script>
js部分
<script>
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
// 随机颜色数组
var colors=['red','origin','yellow','green','cyan','blue','purple','pink','white','skyblue','yellowgreen'];
// 演员数组,将所有小球对象都放进数组
var actors=[];
// 创建小球对象
function Ball(x,y,r){
this.x=x;
this.y=y;
this.r=r;
this.color=_.sample(colors);
// 定义小球方向矢量
this.deltaX=Math.random() * 10 - 5; //-5 ~ 5
this.deltaY=Math.random() * 10 - 5;
// 将创建好的小球放进数组
window.actors.push(this);
}
// 更新方法
Ball.prototype.update=function(){
this.y += this.deltaY;
this.x += this.deltaX;
this.r -= 0.2;
}
// 渲染方法
Ball.prototype.render=function(){
// 判断半径
if(this.r < 0){
actors = _.without(actors,this);
return;
}
// 如果小球半径不小于0
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,7,false);
ctx.closePath();
ctx.fillStyle=this.color;
ctx.fill();
}
// 当鼠标滑动时时候,每一次都会创建一个小球
canvas.onmousemove=function(ev){
new Ball(ev.offsetX,ev.offsetY,15);
}
// 信号量
// 帧编号
var framesNumber=0;
// 帧频 fps
var fps=0;
// _fps临时帧频
var _fps=0;
// 计算帧频的时间间隔
var _timeStamp;
setInterval(function(){
// 清除画布
ctx.clearRect(0,0,canvas.width,canvas.height);
// 打印帧编号
framesNumber++;
ctx.fillStyle='#fff';
ctx.fillText('帧编号:'+framesNumber,10,20);
// 计算fps
if(Date.parse(new Date()) == _timeStamp){
_fps++;
}else{
_timeStamp = Date.parse(new Date());
fps = _fps;
_fps = 0;
}
ctx.fillText('fps:'+fps,10,30);
_.each(actors,function(ball){
ball.update();
ball.render();
})
},-1)
</script>