美文网首页
canvas基础动画及优化

canvas基础动画及优化

作者: 索哥来了 | 来源:发表于2017-07-21 17:08 被阅读0次

闲来无事,整理下这段时间做动画遇到的问题,同时分享一下经验。
最开始的需求是做一个夹娃娃的活动页面。用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基础动画及优化

    闲来无事,整理下这段时间做动画遇到的问题,同时分享一下经验。最开始的需求是做一个夹娃娃的活动页面。用css3-tr...

  • canvas动画实战与性能优化

    插播一篇关于 canvas 动画及性能优化的文章,为我们可以更好的进入到 webgl 的世界奠定基础。 本篇文章的...

  • canvas图表(3) - 饼图

      原文地址:canvas图表(3) - 饼图  这几天把canvas图表都优化了下,动画效果更加出色了,可以说很...

  • Canvas教程(1)——HTML5简介

    前言 今后的一个月内会连载详细的Canvas教程,从零基础开始,到Canvas API,再到基本动画与高级动画的实...

  • Android-UI控件

    手摸手教你写 Slack 的 Loading 动画 四步实现:画布旋转及线条变化动画(Canvas Rotate ...

  • 绚丽的倒计时效果(Canvas)

    1. 案例介绍 最近在慕课网上看了一门有关Canvas的课程案例,炫丽的倒计时效果Canvas绘图与动画基础,学习...

  • Hexo Next 背景动画Canvas_nest: true设

    Canvas_nest背景动画 由于在Next 6.0后设置 Canvas_nest: true 是背景将会有动画...

  • 2018-08-22

    动画技术向 canvas动画,是AN可以输出的吗?json文件又是属于什么动画的?和canvas是不同的格式的吧?

  • HTML5中canvas使用

    1、Canvas基础 2、Canvas画直线 3、Canvas画矩形 4、Canvas画文字 5、Canvas画圆...

  • 程序员做小程序,推荐这几款实用又炫酷的HTML5 Canvas插

    1.HTML5 Canvas 3D旋转地球动画 这是一款基于HTML5 Canvas的3D地球模拟动画,动画以太空...

网友评论

      本文标题:canvas基础动画及优化

      本文链接:https://www.haomeiwen.com/subject/fosekxtx.html