DEV Community

Cover image for Exporting html dom elements as png in javascript
David
David

Posted on

Exporting html dom elements as png in javascript

Intro

I have recently tried to answer this question in order to create a project. But I didn't find a clear answer. So here it is:

import domtoimage from "dom-to-image";

const scale = 5;

//...

function exportAsPNG() {
    domtoimage
      .toBlob(element, {
        //Changing the resolution by a factor (scale)
        //Else this setup might cause blurry images
        width: element.clientWidth * scale,
        height: element.clientHeight * scale,
        style: {
          transform: `scale(${scale})`,
          transformOrigin: "top left",
        },
      })
      .then(blob => {
        saveAs(blob, "image.png");
      });
  }

  function saveAs(blob, fileName) {
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
  }

Enter fullscreen mode Exit fullscreen mode

Walkthrough

The only really intresting thing about this snippet is the scaling part because with a bunch of other libraries the image turns out to be a blurry mess.

For me a scaling factor of 5 worked well. But it is definately a parameter to fine tune.

The saveAs function isn't intresting it just creates an anchor tag, fiddles with the url and clicks it.

Notes

  • Jpeg exports are also possible with the function domtoimage.toJpeg(args)
  • And for svg exports it is domtoimage.toSvg(args)

Links

Discussion (0)