Skip to content

Instantly share code, notes, and snippets.

@olizilla
Created January 3, 2011 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olizilla/763282 to your computer and use it in GitHub Desktop.
Save olizilla/763282 to your computer and use it in GitHub Desktop.
olizilla gets up close and functional with javascript. withCanvas provides a temporary canvas to another function, and always remembers to clean up after itself.
// Provide a function with a temporary canvas, encapsulating the creation and clean up code.
function withCanvas(/*canvas => Any*/ use) {
var b = document.body;
// create canvas
var canvas = document.createElement("canvas");
// canvas doesn't draw well unless it's added to the page
b.appendChild(canvas);
// do the user code
var result = use(canvas);
// clean up
b.removeChild(canvas);
// return anything there is to return
return result;
}
var video = document.getElementById('someVideo');
// usage, do something with a temporary canvas
var src = withCanvas( function(canvas){ // anonymous function, canvas => String
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
return ctx.canvas.toDataURL('image/png');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment