Skip to content

Instantly share code, notes, and snippets.

@IvoPereira
Created January 8, 2015 19:28
Show Gist options
  • Save IvoPereira/042932781b312ba3fade to your computer and use it in GitHub Desktop.
Save IvoPereira/042932781b312ba3fade to your computer and use it in GitHub Desktop.
Take screenshot, convert it to Canvas to be inserted into a PDF (support SVG)
function take(targetElem) {
// First render all SVGs to canvases
var elements = targetElem.find('svg').map(function() {
var svg = $(this);
var canvas = $('<canvas></canvas>');
svg.replaceWith(canvas);
// Get the raw SVG string and curate it
var content = svg.wrap('<p></p>').parent().html();
content = content.replace(/xlink:title="hide\/show"/g, "");
content = encodeURIComponent(content);
svg.unwrap();
// Create an image from the svg
var image = new Image();
image.src = 'data:image/svg+xml,' + content;
image.onload = function() {
canvas[0].width = image.width;
canvas[0].height = image.height;
// Render the image to the canvas
var context = canvas[0].getContext('2d');
context.drawImage(image, 0, 0);
};
return {
svg: svg,
canvas: canvas
};
});
targetElem.imagesLoaded(function() {
// At this point the container has no SVG, it only has HTML and Canvases.
html2canvas(targetElem[0], {
onrendered: function(canvas) {
// Put the SVGs back in place
elements.each(function() {
this.canvas.replaceWith(this.svg);
});
// Do something with the canvas, for example put it at the bottom
$(canvas).appendTo('body');
}
})
})
}
// (uses https://github.com/desandro/imagesloaded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment