网页设计中使用视频的前景(5)
2014-02-19 08:40:38

requestAnimationFrame循环

Charlie.js的心脏是一个运行时的视频上运行一个循环。循环与创建requestAnimationFrame。

tick: function(time){
	if (this.running){
		this.frameID = requestAnimationFrame(this.tick.bind(this));
		this.controller.startAnimations(time, video.currentTime);
	}
}

该requestAnimationFrame功能是专门设计来优化任何类型的动画,比如DOM操作,画到画布上,和WebGL的。它比任何你可以用得到更严格的循环setTimeout的,它的标定捆绑动画步入一个单一的回流,从而进行更好的。它也为电池的使用更好,将完全停止,当用户切换选项卡上运行。

在循环开始时的视频启动和停止时录像停止。Charlie.js还需要知道是否要在影片结束或跳转到中间的某个地方。每个这些事件,需要一个稍微不同的响应。

video.addEventListener("play", this.start.bind(this), false);
video.addEventListener("ended", this.ended.bind(this), false);
video.addEventListener("pause", this.stop.bind(this), false);
video.addEventListener("seeked", this.seeked.bind(this), false);

随着视频的播放,循环不断滴答作响。每个刻度运行这段代码:
 

// allow precision to one tenth of a second
var seconds = roundTime(videoTime),
me = this;

//resume any paused animations
me.resumeAnimations();

/* start up any animations that should be running at this second.
* Don't start any that are already running
*/

if (me.bySeconds[seconds]){
	var animations = me.bySeconds[seconds],
	notRunning = _.filter(animations, function(animation){
		return !_.contains(me.running, animation);
	});

	/* requestAnimationFrame happens more than
	*  every tenth of a second, so this code will run
	*  multiple times for each animation starting time
	*/

	_.forEach(notRunning, function(animation){
		animation.start();
		me.running.push(animation);