father::微信小程序

关键帧动画

在页面或自定义组件中,当需要进行关键帧动画时,可以使用 this.animate 接口:

this.animate(selector, keyframes, duration, callback)

示例

  this.animate('#container', [
    { opacity: 1.0, rotate: 0, backgroundColor: '#FF0000' },
    { opacity: 0.5, rotate: 45, backgroundColor: '#00FF00'},
    { opacity: 0.0, rotate: 90, backgroundColor: '#FF0000' },
    ], 5000, function () {
      this.clearAnimation('#container', { opacity: true, rotate: true }, function () {
        console.log("清除了#container上的opacity和rotate属性")
      })
  }.bind(this))
  this.animate('.block', [
    { scale: [1, 1], rotate: 0, ease: 'ease-out'  },
    { scale: [1.5, 1.5], rotate: 45, ease: 'ease-in', offset: 0.9},
    { scale: [2, 2], rotate: 90 },
  ], 5000, function () {
    this.clearAnimation('.block', function () {
      console.log("清除了.block上的所有动画属性")
    })
  }.bind(this))

滚动驱使的动画

我们发现,根据滚动位置而不断改变动画的进度是一种比较常见的场景,这类动画可以让人感觉到界面交互很连贯自然,体验更好。因此,从小程序基础库 2.9.0 开始支持一种由滚动驱动的动画机制。 基于上述的关键帧动画接口,新增一个 ScrollTimeline 的参数,用来绑定滚动元素(目前只支持 scroll-view)。接口定义如下:

this.animate(selector, keyframes, duration, ScrollTimeline)

示例

this.animate('.avatar', [{
  borderRadius: '0',
  borderColor: 'red',
  transform: 'scale(1) translateY(-20px)',
  offset: 0,
}, {
  borderRadius: '25%',
  borderColor: 'blue',
  transform: 'scale(.65) translateY(-20px)',
  offset: .5,
}, {
  borderRadius: '50%',
  borderColor: 'blue',
  transform: `scale(.3) translateY(-20px)`,
  offset: 1
}], 2000, {
  scrollSource: '#scroller',
  timeRange: 2000,
  startScrollOffset: 0,
  endScrollOffset: 85,
})
this.animate('.search_input', [{
  opacity: '0',
  width: '0%',
}, {
  opacity: '1',
  width: '100%',
}], 1000, {
  scrollSource: '#scroller',
  timeRange: 1000,
  startScrollOffset: 120,
  endScrollOffset: 252
})