May 27, 2013

JavaScript: Throttle requestAnimationFrame to maintain 30fps

One problem with using requestAnimationFrame is that rendering will take place as quickly as the computer can process the per-frame calculations and screen redraw. If you only want to run at 30fps, your computer might be running a lot faster than you want. To work around this problem, simply check the elapsed time before running the next frame update. Check out the example:
var frameLength = 33; // this is ~1/30th of a second, in milliseconds (1000/30)
var lastFrame = 0;

var render = function() {
  if(Date.now() - lastFrame > frameLength) {
    lastFrame = Date.now()

    // run your 30fps code here...
  }
  requestAnimationFrame(render);
};
requestAnimationFrame(render);
You'll notice that I'm using Date.now(), which requires a polyfill for old versions of IE. requestAnimationFrame also requires a polyfill for some browsers. Another solution is to use time-based calculations, but that's not always easy to implement.

May 25, 2013

Bookmarklet: Scrub through a Vine video

I was watching a friend's Vine video on the web, and I got the idea that it would be cool to control the playback of the video. I wrote this little bookmarklet to scrub through the video as you move your mouse over it. Here's the original JavaScript:
// grab video element and pause it
var vid = document.getElementById('post_html5_api'); 
vid.pause(); 
// get x offset of video
var vidX = 0; 
var el = vid;
while (el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
  vidX += el.offsetLeft;
  el = el.offsetParent;
}
// scrub the video based on mouse x
var vidTime = vid.seekable.end(0); 
vid.addEventListener('mousemove', function(e) {
  var x = e.clientX - vidX;
  var percent = x / vid.offsetWidth;
  vid.currentTime = percent * vidTime;
}, false);
And the bookmarklet (Vine Scrubber):
javascript:(function()%7Bvar%20vid=document.getElementById('post_html5_api');vid.pause();var%20vidX=0;var%20el=vid;while(el&&!isNaN(el.offsetLeft)&&!isNaN(el.offsetTop))%7BvidX+=el.offsetLeft;el=el.offsetParent;%7Dvar%20vidTime=vid.seekable.end(0);vid.addEventListener('mousemove',function(e)%7Bvar%20x=e.clientX-vidX;var%20percent=x/vid.offsetWidth;vid.currentTime=percent*vidTime;%7D,false)%7D)();