Created
February 26, 2014 22:23
-
-
Save jfktrey/9239952 to your computer and use it in GitHub Desktop.
Work around SVG drawing issues when capturing screenshot using html2canvas
This file contains 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
// Work around an annoying issue in Chrome where SVG images aren't drawn with respect to globalAlpha | |
window.CanvasRenderingContext2D.prototype.drawSvgImage = function(image, x, y, w, h) { | |
var canvas = document.createElement('canvas'); | |
canvas.width = w; | |
canvas.height = h; | |
var context = canvas.getContext('2d'); | |
context.drawImage(image, 0, 0, w, h); | |
this.drawImage(canvas, x, y, w, h); | |
} | |
// Returns a screenshot using the awesome html2canvas library. Works around SVG issues. | |
function getScreenshot (callback) { | |
html2canvas(document.body, { | |
onrendered: (function (callbackClosure) { | |
return function(renderedCanvas) { | |
var renderedCanvasContext = renderedCanvas.getContext('2d'); | |
renderedCanvasContext.save(); | |
$("object").filter(':visible').each(function(){ | |
var clientRect = this.getBoundingClientRect(); | |
var svgSource = $("svg", $(this).documents()[0])[0].outerHTML; | |
var svgImage = new Image(); | |
svgImage.src = "data:image/svg+xml;base64," + window.btoa(svgSource); | |
renderedCanvasContext.globalAlpha = parseFloat($(this).css("opacity")); | |
renderedCanvasContext.drawSvgImage(svgImage, clientRect["left"], clientRect["top"], clientRect["width"], clientRect["height"]); | |
}); | |
renderedCanvasContext.restore(); | |
callbackClosure(renderedCanvas); | |
}})(callback) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment