动画 球

1.javascript动画

通过javascript在一定周期内不断地改变宽度和高度的值。动画可能没有按照预期的时间执行,因为javascript是单线程的,可能线程被其他的js代码使用而需要等待。可能出现动画不流畅的现象。

#ball
{
    margin: 100px auto;
    background-color: yellow;
    width: 1px;
    height: 1px;
    border-radius: 50%;
    -webkit-border-radius: 50%;
}
var ball = document.getElementById('ball');
    requestAnimationFrame(function draw(){
    var width = ball.offsetWidth,
          height = ball.offsetHeight;
    if(width < 100){
          requestAnimationFrame(draw);
    }
    
    ball.style.width = width + 1 + 'px';
    ball.style.height = height + 1 + 'px';
})

2.css transition

transition使css的属性值在一定的时间内平滑地过渡。

transiton: property duration timing-function delay

#ball{
        margin: 100px auto;
        background-color: yellow;
        width: 1px;
        height: 1px;
        border-radius: 50%;
        transition: all 2s;
        -webkit-transition: all 2s;
    }
var ball = document.getElementById('ball');
setTimeout(function(){
    ball.style.width = '100px';
    ball.style.height = '100px';
},1000)

3.css animation帧动画

创建多个帧,从一个帧样式逐渐变化到另一个帧样式。

animation: name duration timing-function delay iteration-count direction fill-mode play-state

    #ball{
        margin: 100px auto;
        background-color: yellow;
        border-radius: 50%;
        animation: draw 2s infinite alternate;
        -webkit-animation: draw 2s inifinite alternate;
    }
    
    @keyframes draw{
        from {width: 1px;height:1px;}
        to {width: 100px;height: 100px;}
    }
    @-webkit-keyframes draw{
        from {width: 1px;height:1px;}
        to {width: 100px;height: 100px;}
    }

4.canvas

canvas不断擦除与绘制,达到动画效果。

<div> 
    <canvas width="200" height="200" id="myCanvas">
    </canvas>
</div>
var canvas = document.getElementById('myCanvas');
if(canvas.getContext){
    var context = canvas.getContext('2d');
}

function draw(radius){
    context.beginPath();
    context.arc(100,100,radius,0,Math.PI*2,true);
    context.closePath();
    context.fillStyle = 'yellow';
    context.fill();
}

var radius = 1;
var interval = setInterval(function(){
    radius++;
    if(radius >= 50){
    clearInterval(interval);
    return;
    }
    draw(radius);
},20)
原文地址:https://www.cnblogs.com/fe-huahai/p/5647775.html