canvas基础动画及优化

闲来无事,整理下这段时间做动画遇到的问题,同时分享一下经验。
最开始的需求是做一个夹娃娃的活动页面。用css3-transform(translate3d)的时候发现在苹果手机上面页面会有闪动,这个解决办法请参考这篇文章。基友于是推荐我使用canvas实现动画,所以才有下面的研究:
先直接上代码,后面再解释。
1.直线运动:可以直接拉去运行

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#canvas{
    border:1px solid #ccc;
}   
</style>
</head>
<body>
 <canvas id="canvas" width='800' height='500'>你的浏览器不支持canvas,请跟换其他浏览器试一试</canvas>
</body>
<script type="text/javascript">
window.onload=function(){
    var canvas=document.getElementById('canvas'),
        context=canvas.getContext('2d'),
        iWidth = canvas.width,
        iHeight = canvas.height,
        length = 40,//表示矩形(这里画正方形)边长,或者圆半径
        speed = -5;

    context.fillStyle='red';
    context.beginPath();
    context.fillRect((iWidth-length), 0, length, length);//绘制矩形
    context.arc((iWidth-length),(iHeight/2),length,0,2*Math.PI,true);//圆
    context.closePath();
    context.fill();

    var startPoint = iWidth-length;
    setInterval(function(){
        startPoint+=speed;
        if(startPoint<=(-1*length)){
            startPoint=iWidth-length
        }
        run(context,iWidth,iHeight,length,startPoint);
    }, 30);
};

function run(cxt,width,height,length,point){
    cxt.clearRect(0,0,width,height);
    cxt.beginPath();
    cxt.fillRect(point, 0, length, length);
    cxt.arc(point,(height/2),length,0,2*Math.PI,true);
    cxt.closePath();
    cxt.fill();
}
</script>
</html>

效果如图:

image.png

2.环绕运动:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#canvas{
    border:1px solid #ccc;
}   
</style>
</head>
<body>
 <canvas id="canvas" width='800' height='500'>你的浏览器不支持canvas,请跟换其他浏览器试一试</canvas>
</body>
<script type="text/javascript">
window.onload=function(){
    var canvas=document.getElementById('canvas'),
        context=canvas.getContext('2d'),
        iWidth = canvas.width,
        iHeight = canvas.height,
        length = 40//太阳半径

    context.translate((iWidth/2),(iHeight/2));//原点移到画布中心
    drawNotchange(context,length)

    //地球
    context.beginPath();
    context.fillStyle='blue';
    context.arc((length*3),0,length/2,0,2*Math.PI,true);
    context.fill();
    context.closePath();

    var time = 0 
    setInterval(function(){
        run(context,iWidth,iHeight,length,time);
        time+=1;
    }, 30);
    
};

function drawNotchange(ctx,length){

    //太阳
    ctx.beginPath();
    ctx.fillStyle='red';
    ctx.arc(0,0,length,0,2*Math.PI,true);
    ctx.fill();
    ctx.closePath();

    //轨道
    ctx.beginPath();
    ctx.strokeStyle="#ccc";
    ctx.arc(0,0,length*3,0,2*Math.PI,true);
    ctx.stroke();
    ctx.closePath();
}

function run(ctx,iWidth,iHeight,length,time){
    // ctx.clearRect(x,y,w,h);x,y是原点。w,h是宽高
    ctx.clearRect(-iWidth/2,-iHeight/2,iWidth,iHeight);
    drawNotchange(ctx,length);
    ctx.save();//保存不变的渲染

    // 保存后 只对地球操作旋转
    ctx.beginPath();
    ctx.rotate(time*2*Math.PI/180);//旋转角度
    ctx.fillStyle='blue';
    ctx.arc((length*3),0,length/2,0,2*Math.PI,true);
    ctx.fill();
    ctx.closePath();
    ctx.restore();//配合save使用,取出之前save的状态 
}
</script>
</html>
image.png

分析:
canvas动画就是一个不停 绘制-清除-绘制-清除的过程。所以每次绘制前都需要clearRect
矩形绘制:
rect(x,y,w,h):x、y为起始坐标,w、h为矩形的宽、高
fillRect(x,y,w,h):参数同上(本例子用的这个)
区别:上面只绘制、不填充,fillRect()填充

圆形绘制:
arc(x,y,r,sa,ea,true/false):x、y为圆心坐标,r为半径,sa、ea分 别为起始角度和结束角度,最后一个参数为true时,顺时针画圆,false 则逆时针画圆;

第一个例子的运动很简单,就是使用定时器动态改变 x轴坐标值
第二个例子的环绕运动,则主要是用到旋转,这里为了方便,直接使用translate改变了画布的原点。然后清除画布的时候把前两个参数改下就好了,后面两个参数是画布的宽高不用动 ctx.clearRect(x,y,w,h)--x,y是原点。w,h是宽高
还有一点需要注意的是save和restore,这两个方法分别用来保存、恢复canvas的状态 ,无参数;比如第二个例子中,太阳和轨道是静止不动的,我们绘制完之后,要先save起来,然后旋转画布来绘制地球,实现地球的环绕运动。每次绘制地球后,都要使用restore方法恢复显示 太阳和轨道。

上面两个动画很简单,但是发现动画会抖动,所以我们下面不用定时器,用requestAnimationFrame来优化,本文参考网址:http://www.webhek.com/post/requestanimationframe.html
直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script type="text/javascript">
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       || 
            window.webkitRequestAnimationFrame || 
            window.mozRequestAnimationFrame    || 
            window.oRequestAnimationFrame      || 
            window.msRequestAnimationFrame     || 
            function(callback,element){
                window.setTimeout(callback, 1000 / 60);
            };
})();

window.onload = function(){

    var canvas = document.createElement( 'canvas' ),
        context = canvas.getContext( '2d' ),
        banjing = 40,
        time = 0;

    canvas.width = 800;
    canvas.height = 500;
    document.body.appendChild( canvas );
    context.translate((canvas.width/2),(canvas.height/2));
    
    animate();
    function animate(){
        requestAnimFrame( animate );
        draw();
    }

    function draw(){
        
        context.clearRect(-canvas.width/2,-canvas.height/2,canvas.width,canvas.height);

        //太阳
        context.beginPath();
        context.fillStyle='red';
        context.arc(0,0,banjing,0,2*Math.PI,true);
        context.fill();
        context.closePath();

        //轨道
        context.beginPath();
        context.strokeStyle="#ccc";
        context.arc(0,0,banjing*3,0,2*Math.PI,true);
        context.stroke();
        context.closePath();

        context.save();
        context.beginPath();
        context.rotate(time*2*Math.PI/180);//旋转角度
        context.fillStyle='blue';
        context.arc((banjing*3),0,banjing/2,0,2*Math.PI,true);
        context.fill();
        context.closePath();
        context.restore();//配合save使用,取出之前save的状态 

        time += 1;
    }
}
</script>
</html>

3.基于上面的环绕运动,下面做了个拓展。月亮绕地球转,地球自转:
(ps:上面代码地球的公转用的是旋转画布,下面地球的公转和月亮的公转用的是 根据角度,sin和cos算出其(x,y)圆心坐标,地球的自转用的是旋转画布)
代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script type="text/javascript">
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       || 
            window.webkitRequestAnimationFrame || 
            window.mozRequestAnimationFrame    || 
            window.oRequestAnimationFrame      || 
            window.msRequestAnimationFrame     || 
            function(callback,element){
                window.setTimeout(callback, 1000 / 60);
            };
})();

window.onload = function(){

    var canvas = document.createElement( 'canvas' ),
        context = canvas.getContext( '2d' ),
        taiyang_R = 40,//太阳半径
        diqiu_R = 20,//地球半径
        circle_dq = 120,//地球绕太阳转轨道半径
        yueliang_R = 10,//月亮半径
        circle_yl = 40,//月亮绕地球转轨道半径
        diqiu_gz = 3600,//地球绕太阳转的角度的比值
        yueliang_gz = 240,//月亮绕地球转的角度的比值
        diqiu_zz = 100,//地球自转的角度的比值
        time = 0;

    canvas.width = 800;
    canvas.height = 500;
    document.body.appendChild( canvas );
    context.translate((canvas.width/2),(canvas.height/2));
    
    animate();
    function animate(){
        requestAnimFrame( animate );
        draw();
    }

    function draw(){
        
        context.clearRect(-canvas.width/2,-canvas.height/2,canvas.width,canvas.height);

        //太阳
        context.beginPath();
        context.fillStyle='red';
        context.arc(0,0,taiyang_R,0,2*Math.PI,true);
        context.fill();
        context.closePath();

        //地球轨道
        context.beginPath();
        context.strokeStyle="#ccc";
        context.arc(0,0,circle_dq,0,2*Math.PI,true);
        context.stroke();
        context.closePath();


        // 2--地球+月亮绕(不旋转) + 地球自转(旋转)
        // 月亮轨道
        context.beginPath();
        context.strokeStyle="#ccc";
        context.arc(circle_dq*Math.cos(time*2*Math.PI/diqiu_gz),circle_dq*Math.sin(time*2*Math.PI/diqiu_gz),circle_yl,0,2*Math.PI,true);
        context.stroke();
        context.closePath();

        // 月亮
        context.beginPath();
        context.fillStyle = 'yellow';
        context.arc( circle_dq*Math.cos(time*2*Math.PI/diqiu_gz) + circle_yl*Math.cos(time*2*Math.PI/yueliang_gz) , circle_dq*Math.sin(time*2*Math.PI/diqiu_gz) + circle_yl*Math.sin(time*2*Math.PI/yueliang_gz) ,yueliang_R,0,2*Math.PI,true);
        context.fill();
        context.closePath();

        // 自转的地球
        context.translate(Number(circle_dq*Math.cos(time*2*Math.PI/diqiu_gz)),Number(circle_dq*Math.sin(time*2*Math.PI/diqiu_gz)));
        context.save();
        context.beginPath();
        context.rotate(time*2*Math.PI/diqiu_zz);//旋转角度
        context.fillStyle='blue';
        context.arc(0,0,diqiu_R,0,2*Math.PI,true);
        context.fill();

        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.strokeStyle = '#fff';
        context.strokeText('地',0,0);
        context.stroke();

        context.closePath();
        context.restore();
        context.translate(-Number(circle_dq*Math.cos(time*2*Math.PI/diqiu_gz)),-Number(circle_dq*Math.sin(time*2*Math.PI/diqiu_gz)));
        
        time += 1;
    }
}
</script>
</html>
image.png

注意事项:
为了实现地球的自转,当在draw函数里面转移画布的原点时,新的坐标一定是相对此次原点来的,比如说我上面的代码,在函数开始之前,把画布中心转移到了太阳的中心,但是要在这基础上转移到地球的中心,就只需要算出地球中心到太阳中心的横竖距离,不需要加上太阳中心相对画布左上角的距离

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一:canvas简介 1.1什么是canvas? ①:canvas是HTML5提供的一种新标签 ②:HTML5 ...
    GreenHand1阅读 10,188评论 2 32
  • 一、canvas简介 1.1 什么是canvas?(了解) 是HTML5提供的一种新标签 Canvas是一个矩形区...
    Looog阅读 9,364评论 3 40
  • 一、canvas简介 1.1 什么是canvas?(了解) 是HTML5提供的一种新标签 Canvas是一个矩形区...
    J_L_L阅读 5,468评论 0 4
  • 线条样式 绘制直线,第五章知识简单回顾 lineWidth 设置或返回当前的线条宽度,单位为像素 lineCap ...
    Zd_silent阅读 3,398评论 0 0
  • 赵文琪(秦羽墨)是一位标准城市美女代表,曾与林浩然(海外新锐导演)有过一段婚史,后分开,赵文琪称当时太年轻,辜负了...
    神枪工作室阅读 3,520评论 1 1