DOM to PNG Directly in the Browser

You could design something on the web then take a screenshot of it. That is, in a basic sense, converting DOM to PNG. But a screenshot is rather manual and finicky. If you had to do this over and over, or you needed a very exact size (like a social media card), you can actually produce a PNG right from the browser with the click of a button. No backend service needed, like Puppeteer or Playwright which are often thought of for this type of automatic screenshotting job.

The trick is that you can render DOM to a <canvas>, thanks to the very fancy html2canvas library. Then you can use .toDataURL() to get it into PNG format and ultimately download it. I always reference Andrew Walpole’s Pen to see it done, which also happens to be a rather elegant Petite Vue example, and the contenteditable usage is a clever way to make it even more usable.

One response to “DOM to PNG Directly in the Browser”

  1. Thanks for the shoutout! Html2canvas is a very underrated library, but also a bit unmaintained. Not to say it doesn’t work, it has aged quite decently actually! But I regularly worry that some new browser/CSS feature will really start to trip it up.

Leave a Reply

Your email address will not be published. Required fields are marked *