Data, Maps, Usability, and Performance

HTML5 Canvas Animation Converted to Video

Last updated on April 6, 2015 in Development

I was recently playing around with dat.gui and the cool FizzyText animation made me consider the concept of exporting HTML5 Canvas to video. I have previously covered canvas to video conversion but it was specific to making a photo slideshow. Today, I want to create a simple script in JavaScript that will grab any CANVAS element, on any website, retrieve the image frames, and compile them into a video file.

Whammy, a JavaScript WebM Encoder, provides a few methods to work with images and HTML5 CANVAS to build a video file. It gets us 90% there but I quickly ran into a problem of alpha transparancy with WebP image format. While the WebP image format now has alpha transparency, the CANVAS toDataURL method encodes the image from RGB pixels and does not support the alpha channel.

This is why converting CANVAS to a WebP image via toDataURL(“image/webp”) often gave me a black screen. Using libwebpjs, a custom implementation of the WEBP format, is an option but seems over complicated. All I really want to do is set the backgroud color when generating an image from Canvas and that should be possible with globalCompositeOperation. I quickly found this great function that returns Canvas as a png based data url with a specified background color and changed it to return WebP format with a white background.

Now, we just need a setInterval loop to start grabbing each frame from Canvas in WebP format and passing that to Whammy.js so it can compile and generate a WebM video out of a Canvas Animation. Here is the code that I ran on the Dat.GUI example and it created the video in my Chrome browser:

It’s probably a good idea to leverage requestAnimationFrame and WebWorkers to pull the image data from Canvas initially, store the frames in an array, and then do the WebP conversion and video generation via Whammy.fromImageArray(image[], fps) but I will experiment with that in another post.


libwebpjs demo
WebP + Alpha Channel via PNG
JPEGs with Alpha Channels
Weppy – Javascript WebP Library
RecordRTC: WebRTC audio/video recording
yt-giffer: youtube video to gif
WebRTC and Whammy.js

Tags: , , , ,

Facebook Twitter Hacker News Reddit More...