解决微信小程序上定义动画createanimation无效

开发项目过程中,想要这样一个动画效果:写一个气泡,有动弹效果(类似呼吸,一直动),点击之后移动至消失。

  • 一开始我在气泡元素上面定义了一个动弹动画:
    在这里插入图片描述
  • 下一步就要写点击事件之后的另一个移动至消失的动画了。
//wxml
<view id="pra-bubble" animation="{{animation}}" bindtap="onClick">


//js
//定义动画,https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/wx.createAnimation.html
this.animation = wx.createAnimation({
     timingFunction: 'ease-in'
 })
 onClick(e) {
   //调用动画的函数
   this.fly();
 }

fly(x=187, y = 197) {
  //获取气泡元素
  const query = this.createSelectorQuery();
  query.select("#pra-bubble").boundingClientRect();
  query.exec(res => {
  const {top, left, width, height} = res[0];
  //...
  this.ani.translate(dx, dy).opacity(0).step({
       duration: 200,
       timingFunction: 'linear'
   })
   this.setData({
       animation: this.ani.export()
   })
 })
}

问题来了,这样定义之后发现点击的动画没有效果,检查了也没错。最后才知道是因为气泡元素的css已经定义了animation,所以js写的动画无效,只需要将css的动画去掉即可。

后面是将一直动弹的动画也写在js,同一个animation里,代码如下

//  bubbleMove函数要在一开始的ready生命周期里调用;

bubbleMove() {
     //随机上下移动的效果
     // 随机时间   400-1000ms
     let t = Math.round(Math.random() * 400 + 1000);
     // Y轴位移  -10-10px
     let y = Math.round(Math.random() * 10 - 10);
     this.ani.translateY(y).step({
         duration: t,
     })
     this.setData({
         animation: this.animation.export()
     })
     this.timeout = setTimeout(()=> {
         this.bubbleMove();   //每隔1s调用一次
     }, 1000)
 },
Logo

分享最新的 NVIDIA AI Software 资源以及活动/会议信息,精选收录AI相关技术内容,欢迎大家加入社区并参与讨论。

更多推荐