Saturday, May 12, 2012

Popcorn.js with html5 slides

I heard about popcorn.js for a while, but did not have a chance to try it out. When the video of one of my talks became available, I knew I found a nail for this lovely hammer: I'll use popcorn.js to synchronize my slides to the video!

It only took a minute to embed the vimeo video. Next I wanted to change the size, so I added style="width: 160px; height: 120px" to the div container. No video. Baffled, I scoured the web for popcorn.js demos, and compared the source code with mine. By process of elimination I discovered that my html5 slides was to blame. The body tag has display: none so the unstyled articles tags do not show, but this means when popcorn.js cannot measure the size of the div container, it got zero width and height. As a work around, I added document.body.style.display = "block" after the html5 slides are initialized, but before I create the popcorn object.

Next I annotated the slides with timings from the video. I extracted the timings and use the Code plugin to update the slide. The first jump worked. But when I added a second one, the slides were no longer moving.

My code looked like this:

for (var i = 0; i < articles.length; ++i) {
  var article = articles[i];
  var timing = getTiming(article);
  pop.code({
    start: timing,
    onStart: function(options) {
      gotoSlide(i);
    }
  });
}

After a lot of experimentation, I finally got it to work:

for (var i = 0; i < articles.length; ++i) {
  var article = articles[i];
  var timing = getTiming(article);
  pop.code({
    start: timing,
    slideNumber: i,
    onStart: function(options) {
      gotoSlide(options.slideNumber);
    }
  });
}

Notice how I stash away the value of i in the hash as slideNumber and grab it from the options inside the onStart callback. What happend was that when I use the variable i directly in the callback, its value has been changed by the for-loop when the callback is executed, so it ended up calling gotoSlide(article.length), which is not valid.

My slides now have a small video playing in the top right corner, which auto-advances the slides when you start watching. Have a look and let me know what you think!

http://www.sqisland.com/talks/fluid-android-layouts

No comments:

Post a Comment

Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.