Skip to content

Instantly share code, notes, and snippets.

@lucasmenendez
Created February 27, 2020 15:50
Show Gist options
  • Save lucasmenendez/e4fc1b02a481012870c013fe1119099d to your computer and use it in GitHub Desktop.
Save lucasmenendez/e4fc1b02a481012870c013fe1119099d to your computer and use it in GitHub Desktop.
Simple class to download SVG inline graphics directly from the browser in PNG format
class SVGDownloader {
constructor(source, filename = "download") {
this.filename = filename;
this.createCanvas(source.clientWidth, source.clientHeight);
this.createImage(source);
}
createCanvas(width, height) {
this.canvas = document.createElement("canvas");
this.canvas.width = width;
this.canvas.height = height;
this.ctx = this.canvas.getContext("2d");
this.ctx.fillStyle = "white";
this.ctx.fillRect(0, 0, width, height);
}
createImage(source) {
let data = new XMLSerializer().serializeToString(source);
let img = new Image();
let blob = new Blob([data], { type: "image/svg+xml;charset=utf-8" });
let url = window.URL.createObjectURL(blob);
img.onload = () => {
this.ctx.drawImage(img, 0, 0);
this.download();
};
img.src = url;
}
download() {
let link = document.createElement("a");
link.download = `${this.filename}.png`;
link.href = this.canvas.toDataURL("image/png");
link.dataset.downloadurl = ["image/png", link.download, link.href].join(":");
link.click();
}
}
export default SVGDownloader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment