Vue中使用create-keyframe-animation与动画钩子完成复杂动画

2020-06-13 10:35:56易采站长站整理

<img src="../assets/bj.png" alt="" class="bg">
</div>
</transition>

计算偏移量(中心点到中心的偏移,图中红线距离)

 


// 获得偏移量,以及scale
_getPosAndScale() {
// 左下角图片的宽度
const targetWidth = 40
// cd宽度
const width = 300
const scale = targetWidth / width
// 这里的 x,y要算,过程省略,无非就是加加减减,这的x,y都是算出来了的
const x = -167.5
const y = 497
return {x ,y , scale}
},

x,y的数值代表什么?见图

 

这里x为什么是负的,y是正的呢?

因为

浏览器的坐标系的中心点是在左上角
的,如图

那么动画从 cd中心到左下角,X偏移为负,y偏移为正

然后用animations插件执行动画钩子


// enter是指当 cd从隐藏到显示的动画,
enter(el, done) {
const {x, y, scale} = this._getPosAndScale()

let animation = {
// 第0帧的时候,先让图片缩小,显示在右下角
0: {
transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
},
// 60%的时候,让图片回到cd中心,变大
60: {
transform: `translate3d(0 ,0 , 0) scale(1.1)`
},
// 变回原来的尺寸,会有一个回弹的效果
100: {
transform: `translate3d(0 ,0 , 0) scale(1)`
}
}
// 动画的一些配置
animations.registerAnimation({
name: 'move',
animation,
presets: {
duration: 400,
easing: 'linear'
}
})
//运行动画
animations.runAnimation(this.$refs.cdWrapper, 'move', done)
},
afterEnter(){
//运行完动画之后,注销掉动画
animations.unregisterAnimation('move')
this.$refs.cdWrapper.style.animation = ''
},
// leave是指 cd从显示到隐藏的动画
leave(el, done) {
this.$refs.cdWrapper.style.transition = 'all 0.4s'
const {x, y, scale} = this._getPosAndScale()
// 这里我们只要直接移动变小就可以了
this.$refs.cdWrapper.style['transform'] = `translate3d(${x}px,${y}px,0) scale(${scale})`

// 监听transitionend 事件在 CSS 完成过渡后触发done回调
this.$refs.cdWrapper.addEventListener('transitionend', () => {
done()
})
},
afterLeave() {
this.$refs.cdWrapper.style.transition = ''
this.$refs.cdWrapper.style['transform'] = ''
}

写到这里,我们就把刚开始的效果给写完啦!