Skip to content

Instantly share code, notes, and snippets.

@Ahrengot
Created November 28, 2016 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ahrengot/76762bc8931d9b06dbef54ca517b7a07 to your computer and use it in GitHub Desktop.
Save Ahrengot/76762bc8931d9b06dbef54ca517b7a07 to your computer and use it in GitHub Desktop.
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