六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 141|回复: 0

html5 实现动画(二)

[复制链接]

升级  97.67%

153

主题

153

主题

153

主题

举人

Rank: 3Rank: 3

积分
493
 楼主| 发表于 2013-1-29 13:48:13 | 显示全部楼层 |阅读模式
<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[0]= new Box("red",3,2,10,35,2,10);//速度10
        boxes[1]= new Box("blue",60,28,44,15,5);//速度20
        boxes[2]= new Box("green",130,200,23,18,10);//速度30
        boxes[3]= new Box("pink",200,150,35,10,20);//速度40
        //开始动画绘制
        interval = setInterval(function(){
            for(var i=0;i<boxes.length;i++){
                //取出一个方块
                var box=boxes[i];
                //清空这个方块
                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>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表