Created
November 28, 2016 15:11
-
-
Save Ahrengot/76762bc8931d9b06dbef54ca517b7a07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'underscore'; | |
import '../lib/gsap/TweenMax'; | |
import '../lib/preloadjs-0.6.1.combined'; | |
import EventEmitter from '../util/event-emitter'; | |
class CanvasPlayer { | |
constructor(opts) { | |
this.opts = _.defaults(opts || {}, this.getDefaultOpts()); | |
this.state = this.getInitialState(); | |
this.init(); | |
} | |
getInitialState() { | |
return { | |
loading: false, | |
currFrame: 0, | |
playing: false, | |
images: this.getImages() | |
}; | |
} | |
getDefaultOpts() { | |
return { | |
width: 960, | |
height: 540, | |
numFrames: 0, | |
baseUrl: '', | |
ext: '.jpg', | |
autoLoad: true, | |
preloadEl: document.querySelector('.product-animation-preloader p') | |
}; | |
} | |
init() { | |
_.bindAll(this, 'onImagesLoaded', 'onImagesLoadProgress'); | |
this.createEl(); | |
if ( this.opts.autoLoad ) { | |
this.load(); | |
} | |
} | |
getImages() { | |
return _.times(this.opts.numFrames, function(num) { | |
return { | |
id: num, | |
src: this.opts.baseUrl + num + this.opts.ext | |
}; | |
}, this); | |
} | |
load() { | |
this.state.loading = true; | |
this.loadQueue = new createjs.LoadQueue(); | |
this.loadQueue.setMaxConnections(10); | |
this.loadQueue.on("complete", this.onImagesLoaded); | |
this.loadQueue.on("progress", this.onImagesLoadProgress); | |
this.loadQueue.loadManifest(this.state.images); | |
} | |
onImagesLoaded() { | |
this.state.loading = false; | |
TweenMax.to(this.opts.preloadEl, 0.6, { | |
opacity: 0, | |
scale: 0.8, | |
onComplete: () => { | |
this.trigger('ready'); | |
} | |
}) | |
} | |
onImagesLoadProgress() { | |
this.opts.preloadEl.innerHTML = Math.round(this.loadQueue.progress * 100) + "%"; | |
} | |
createEl() { | |
this.el = document.createElement('canvas'); | |
this.el.width = 960; | |
this.el.height = 540; | |
this.ctx = this.el.getContext('2d'); | |
} | |
drawImage(id) { | |
this.ctx.drawImage(this.loadQueue.getResult(id), 0, 0); | |
} | |
playTo(frame, duration) { | |
TweenMax.killTweensOf(this.state); | |
TweenMax.to(this.state, duration, { | |
currFrame: frame, | |
roundProps: ['currFrame'], | |
ease: Linear.easeNone, | |
onStart: () => { | |
this.state.playing = true; | |
this.trigger('step_anim_start', frame); | |
}, | |
onUpdate: () => { | |
this.drawImage(this.state.currFrame); | |
}, | |
onComplete: () => { | |
this.state.playing = false; | |
this.trigger('step_anim_complete', frame); | |
} | |
}); | |
} | |
} | |
_.extend(CanvasPlayer.prototype, EventEmitter); | |
export default CanvasPlayer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment