Skip to content

Instantly share code, notes, and snippets.

@bodil
Created May 27, 2014 16:29
Show Gist options
  • Save bodil/bd4c8f0f1f1a51ac5548 to your computer and use it in GitHub Desktop.
Save bodil/bd4c8f0f1f1a51ac5548 to your computer and use it in GitHub Desktop.
Tween.js + Bacon.js === <3
///<reference path="dts/tween.js.d.ts" />
///<amd-dependency path="tween" />
import b = require("./bacon");
import graph = require("./graph");
import ev = require("./events");
module TweenEffects {
var Tween = require("tween.js").Tween;
export var Easing: TweenEasing = require("tween.js").Easing;
export var Interpolation: TweenInterpolation = require("tween.js").Interpolation;
export interface IEffectEvent extends ev.IEvent {
id: string;
asset?: string;
transform?: graph.Transform;
}
/**
* A stream which tweens the element `id` over `duration` ms from transform `from`
* to transform `to`.
*/
export function tween(id: string, duration: number, from: graph.Transform, to: graph.Transform, easing?: (k: number) => number, interpolation?: (v: number[], k: number) => number): b.EventStream<ev.IEvent> {
// Dijkstra would not have liked this.
var tweenDone = false;
// graph.Transform.toJSON() yields a plain JS object suitable for tweening
var tweenValue = from.toJSON();
var t = new Tween(tweenValue);
t.to(to.toJSON(), duration);
if (easing) {
t.easing(easing);
}
if (interpolation) {
t.interpolation(interpolation);
}
t.onComplete(() => { tweenDone = true; });
return b.fromBinder<ev.IEvent>((sink) => {
var ticks = b.ticks();
ticks.take(1).onValue((timestamp) => t.start(timestamp));
ticks.skip(1).onValue((timestamp) => {
if (tweenDone) {
return b.noMore;
}
t.update(timestamp);
if (sink(new b.Next({
type: "effect",
id: id,
transform: from.assoc(tweenValue)
})) === b.noMore) {
tweenDone = true;
}
if (tweenDone) {
sink(new b.End<ev.IEvent>());
return b.noMore;
}
});
return () => {
tweenDone = true;
};
});
}
}
export = TweenEffects;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment