Created
January 8, 2015 19:28
-
-
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)
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
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