Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Explosion-Scratch
Created October 4, 2021 19:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Explosion-Scratch/f37d65e14c5b05457181f349d95d7bd6 to your computer and use it in GitHub Desktop.
Save Explosion-Scratch/f37d65e14c5b05457181f349d95d7bd6 to your computer and use it in GitHub Desktop.
Converts a string of HTML to an image.
function htmlToImage(html, { x = 0, y = 0, width = 300, height = 400 }) {
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
return new Promise((res) => {
var xml = toXML(html);
xml = xml.replace(/\#/g, "%23");
var data = `data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject width="100%" height="100%">${xml}</foreignObject></svg>`;
var img = new Image();
img.onload = function () {
ctx.drawImage(img, x, y, width, height);
res(canvas.toDataURL());
};
img.src = data;
});
function toXML(html) {
var doc = document.implementation.createHTMLDocument("");
doc.write(html);
doc.documentElement.setAttribute("xmlns", doc.documentElement.namespaceURI);
html = new XMLSerializer().serializeToString(doc.body);
return html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment