Web Animation Api 入门

Web Animation Api 入门

<img src="http://cdn.tutorialzine.com/w... alt="Getting Started With The JavaScript Web Animation API" title="Getting Started With The JavaScript Web Animation API"/>

在网页中使用动画提供了更好的用户体验,例如抽屉式菜单。

目前为止,web动画可以通过css3 transitions,css3 keyframes或者其他的动画库(animate.css、Velocity、tween),现在我们可以使用js编写更加自由的web动画,那就是web animation。

创建动画

我们分别用css3和web animation api写个简单的demo用来展示web animation的特性。

Demo

  • css方法

var square = document.getElementById('square');
    
square.addEventListener('click', function() {
    square.className += " animate";
});

.animate {
    animation-name: move-and-change-color;   
    animation-duration: 0.4s;
    animation-fill-mode: forwards;
}

@keyframes move-and-change-color {
    0% {
        transform: translateX(0);
    }

    80% {
        transform: translateX(100px);
        background-color: #2196F3;
    }

    100% {
        transform: translateX(100px);
        background-color: #EF5350;
    }
}
  • Web Animation方法

var moveAndChangeColor = [
    { 
        transform: 'translateX(0)',
        background: '#2196F3'    // blue
    },
    { 
        offset: 0.8,
        transform: 'translateX(100px)', 
        background: '#2196F3'    // blue
    },
    {
        transform: 'translateX(100px)',
        background: '#EF5350'    // red
    }
]; //数组中的每个对象代表一个动画状态

var circle = document.getElementById('circle');
  
circle.addEventListener('click', function() {
    circle.animate(moveAndChangeColor, {
        duration: 400,
        fill: 'forwards'
    });
});

控制动画

通过上面的例子可以简单的对比出,css3方法局限性较大,并不适合复杂的动画,也不易于控制,而Web Animation Api适合复杂动画,并且易于控制。

var animation = elem.animate(transitions, options);

Web Animation Api 提供如下方法:

  • pause() – 暂停动画

  • play() – 播放动画

  • reverse() – 反向播放

  • finish() – 立即结束动画

  • cancel() – 取消动画并回到初始状态

具体使用方法请看Demo

属性和事件监听

动画运行的过程中会通过animate返回动画属性对象,比如动画播放速率-playbackrate,移步Demo

此外,我们还可以监听finishcancel事件做点其他有意义的事情

spinnerAnimation.addEventListener('finish', function() {
    // Animation has completed or .finish() has been called.
    doSomething();
});

spinnerAnimation.addEventListener('cancel', function() {
    // Animation has been canceled.    
    doSomething();
});

兼容性

大部分chrome、firefox都支持Web Animation Api,其他的例如ios、安卓都不支持,详情请查看Caniuse

对于不支持的可以是用polyfill

相关资料

原文地址

Getting Started With The JavaScript Web Animation API

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值