Created
October 4, 2021 19:07
-
-
Save Explosion-Scratch/f37d65e14c5b05457181f349d95d7bd6 to your computer and use it in GitHub Desktop.
Converts a string of HTML to an image.
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
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