Skip to content

Instantly share code, notes, and snippets.

@cacheflowe cacheflowe/render-svg.js
Last active Nov 27, 2016

Embed
What would you like to do?
Render svg to bitmap
var renderSVG = function(svgEl, renderedCallback, jpgQuality) {
// WARNING! Inline <image> tags must have a base64-encoded image as their source. Linked image files will not work.
// transform svg into base64 image
var s = new XMLSerializer().serializeToString(svgEl);
var uri = 'data:image/svg+xml;base64,' + window.btoa(s);
// load svg image into canvas
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
if(jpgQuality > 0.2) {
var jpg = canvas.toDataURL('image/jpeg', jpgQuality);
renderedCallback(jpg);
} else {
var png = canvas.toDataURL('image/png');
renderedCallback(png);
}
}
image.src = uri;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.