Skip to content

Instantly share code, notes, and snippets.

@yongjun21
Last active February 16, 2019 01:58
Show Gist options
  • Save yongjun21/3f1e9c47d1677a9e011f74e0b1528a96 to your computer and use it in GitHub Desktop.
Save yongjun21/3f1e9c47d1677a9e011f74e0b1528a96 to your computer and use it in GitHub Desktop.
Directive to animate SVG element in Vue
/*
Example usage:
<rect v-for="bar in bars" :key="bar.key" v-animated="bar.attrs"></rect>
*/
import {TweenMax} from 'gsap/TweenMax'
const currentAnimations = {}
export default {
bind (el, binding) {
el.classList.add('animated')
Object.keys(binding.value).forEach(prop => {
el.setAttribute(prop, binding.value[prop])
})
},
update (el, binding) {
const key = binding.arg || 'default'
const attr = Object.assign({}, binding.value)
const duration = attr.duration || 0.3
const priority = attr.priority || 0
delete attr.duration
delete attr.priority
const tween = TweenMax.to(el, duration, {
attr,
onStart: () => el.classList.add('animating'),
onComplete: () => el.classList.remove('animating')
})
if (key in currentAnimations) currentAnimations[key].push([priority, tween])
}
}
export function queueAnimations (...keys) {
if (keys.length > 0) {
keys.forEach(key => {
currentAnimations[key] = []
})
} else {
currentAnimations['default'] = []
}
}
export function flushAnimations (key = 'default') {
if (!(key in currentAnimations)) return []
const queued = currentAnimations[key]
delete currentAnimations[key]
return queued.sort((a, b) => a[0] - b[0]).map(r => r[1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment