Last active
November 22, 2017 23:04
-
-
Save jbouny/85a1c0974b794f4e7b80 to your computer and use it in GitHub Desktop.
Node.js WebM generation with whammy and sharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Whammy = require('node-whammy'), | |
sharp = require('sharp'); | |
function canvasToWebp(canvas, callback) { | |
sharp(canvas.toBuffer()).toFormat(sharp.format.webp).toBuffer(function(e, webpbuffer) { | |
var webpDataURL = 'data:image/webp;base64,' + webpbuffer.toString('base64'); | |
callback(webpDataURL); | |
}); | |
} | |
function sendAsWEBP(response, canvas) { | |
var encoder = new Whammy.Video(7); | |
var currentId = 0, | |
time = 0, | |
timeout = 20000, | |
delay = 20 | |
addedFrame = -1, | |
totalFrames = 3, | |
tmpFrames = Array.apply(null, Array(totalFrames)); | |
var addFrame = function addFrame(context) { | |
var id = currentId++; | |
canvasToWebp(context.canvas, function(webmData) { | |
tmpFrames[id] = webmData; | |
for(var i = addedFrame + 1; i < totalFrames; ++i) { | |
if(tmpFrames[i] !== undefined) { | |
encoder.add(tmpFrames[i]); | |
addedFrame = i; | |
} | |
else { | |
break; | |
} | |
} | |
}); | |
}; | |
var checkReady = function checkReady() { | |
if(totalFrames <= addedFrame + 1) { | |
try { | |
var output = encoder.compile(true); | |
response.type('webm'); | |
response.send(new Buffer(output)); | |
console.log('Webm compilation: ' + time + 'ms'); | |
} | |
catch(err) { | |
response.send(err.toString()); | |
} | |
} | |
else if((time += delay) < timeout) { | |
setTimeout(checkReady, delay); | |
} | |
else { | |
response.send('Timeout of ' + timeout + 'ms exceed'); | |
} | |
}; | |
var context = canvas.getContext("2d"); | |
// Add 3 frames | |
addFrame(context); | |
addFrame(context); | |
addFrame(context); | |
setTimeout(checkReady, delay); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment