wjlgryx 发表于 2013-1-24 06:42:26

html5 实现动画(二)

<canvas id="canvas2" width="250" height="300" style="background-color:black">
    你的浏览器不支持 Canvas 标签,请使用 Chrome 浏览器 或者 FireFox 浏览器
</canvas><br/>
<input type="button" value="开始" />
<input type="button" value="暂停" />
<script type="text/javascript">
    //定时器
    var interval=null;
    //停止动画
    function stop(){
      clearInterval(interval);
    }
    //===================================================================
    //重新组织代码
    //====================================================================
    //方块的构造函数
    function Box(color,x,y,w,h,delta){
      this.color=color;
      this.x=x;
      this.y=y;
      this.w=w;
      this.h=h;
      this.delta=delta;
      //三十帧
      this.fps=30;
      //每一帧的延迟时间
      this.delay=1000/this.fps;
      //上一次重绘的时间
      this.last_update=0;
    }
    //方块更新
    Box.prototype.update=function(canvas){
      //获取当前时间
      var now=(new Date()).getTime();
      //如果达到了延迟时间,则更新数据
      if((now-this.last_update)>this.delay){
            //改变 y 坐标
            this.y=this.y+this.delta;
            //上边缘检测
            if(this.y<0){
                this.y=0;
                this.delta=-this.delta;
            }
            //下边缘检测
            if((this.y+this.h)>canvas.getAttribute("height")){
                this.y=canvas.getAttribute("height")-this.h;
                this.delta=-this.delta;
            }
            //记下最新一次绘制时间
            this.last_update=now;
      }
    }
    function move_box2(){
      //停止动画
      stop();
      //画布对象
      var canvas=document.getElementById("canvas2")
      //获取上下文对象
      var ctx = canvas.getContext("2d");
      //清空画布
      ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height"));
      //创建多个方块对象
      var boxes=[];
      boxes= new Box("red",3,2,10,35,2,10);//速度10
      boxes= new Box("blue",60,28,44,15,5);//速度20
      boxes= new Box("green",130,200,23,18,10);//速度30
      boxes= new Box("pink",200,150,35,10,20);//速度40
      //开始动画绘制
      interval = setInterval(function(){
            for(var i=0;i<boxes.length;i++){
                //取出一个方块
                var box=boxes;
                //清空这个方块
                ctx.clearRect(box.x,box.y,box.w,box.h);
                //更新数据
                box.update(canvas);
                //保存状态
                ctx.save();
                //设置颜色
                ctx.fillStyle=box.color;
                //移动坐标
                ctx.translate(box.x,box.y);
                //重新绘制
                ctx.fillRect(0,0,box.w,box.h);
                //恢复状态
                ctx.restore();
            }
      },1);//尽可能快的循环
    }
</script>
页: [1]
查看完整版本: html5 实现动画(二)