Converts a string of HTML to an image.

PHOTO EMBED

Thu Dec 16 2021 22:58:19 GMT+0000 (UTC)

Saved by @Explosion #javascript #canvas #html

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;
  }
}
content_copyCOPY

https://gist.github.com/Explosion-Scratch/f37d65e14c5b05457181f349d95d7bd6