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;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter