当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS抛物线动画实例制作

JS抛物线动画实例制作

2018年03月07日  | 移动技术网IT编程  | 我要评论

在做无人便利小程序的项目中,某一天产品说要像某产商产品学习,给添加购物车增加抛物线小球动画。好吧,产品你最大,做!

先给大家看下效果图

分析

这种不固定起始位置的动画,自然不能用 gif 图,所以只能用原生代码实现

那我们有什么工具来实现动画呢?

小程序提供了 js api createanimation 来创建动画

css animation

工具有了,我们再看一下什么是抛物线。

这里我们只讨论水平抛物线,水平抛物线从数学原理上来说就是【水平匀速、垂直加速的运动】,转换成代码层面就是在动画效果 timingfunction 中,水平动画采用 linear ,垂直动画采用 ease-in

所以我们需要把这个抛物线动画分解成 两个 同时 进行但 不同动画效果 的动画。

实现

小程序的实现

js:

cartanimation(x, y) { // x y 为手指点击的坐标,即球的起始坐标
  let self = this,
    carty = app.globaldata.winheight - 50, // 结束位置(购物车图片)纵坐标
    cartx = 50, // 结束位置(购物车图片)的横坐标
    animationx = flyx(cartx, x), // 创建球的横向动画
    animationy = flyy(carty, y), // 创建球的纵向动画
    this.setdata({
      ballx: x,
      bally: y,
      showball: true
    })
  settimeoutes6(100).then(() => { // 100 秒延时,确保球已经到位并显示
    self.setdata({
      animationx: animationx.export(),
      animationy: animationy.export(),
    })
    return settimeoutes6(400) // 400 是球的抛物线动画时长
  }).then(() => { // 400 秒延时后隐藏球
    this.setdata({
      showball: false,
    })
  })
}

function settimeoutes6(sec) { // promise 化 settimeout
  return new promise((resolve, reject) => {
    settimeout(() => {resolve()}, sec)
  })
}

function flyx(cartx, orix) { // 水平动画
  let animation = wx.createanimation({
    duration: 400,
    timingfunction: 'linear',
  })
  animation.left(cartx).step()
  return animation
}

function flyy(carty, oriy) { // 垂直动画
  let animation = wx.createanimation({
    duration: 400,
    timingfunction: 'ease-in',
  })
  animation.top(carty).step()
  return animation
}

html:

<view animation="{{animationy}}" style="position:fixed;top:{{bally}}px;" hidden="{{!showball}}">
  <view class="ball" animation="{{animationx}}" style="position:fixed;left:{{ballx}}px;"></view>
</view>

据我所知,用 transform: transtate() 来实现的动画会比 top & left 性能更优,但尝试下来发现并不能做到理想的交互效果,期待后续继续研究吧

h5 的实现

// todo

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网