Export canvas as an image

I've been tinkering with generative art in p5.js. To write my small sketches I've built a small tool with live reloading in Node.js which let's me choose which sketch to currently work on in the browser. I wanted a button across all sketches which would download and save sketches as an image onto my computer. p5.js has this built in but since I needed to share this functionality cross my sketches, I went looking for a native solution in JavaScript.

The easiest way was to fetch the <canvas> element, convert the sketch into a data URI and redirect the page to the file.

const canvas = document.querySelector('canvas');

window.location = canvas
  .toDataURL('image/png')
  .replace('image/png', 'image/octet-stream');

This works great except for one small (read big) downside. It isn't possible to name the file. Instead I'd to create an <a> element, set the download attribute and then click the link programmatically. This let me name the file before saving it.

const canvas = document.querySelector('canvas');
const link = document.createElement('a');

link.download = 'sketch-092.png';

link.href = canvas
  .toDataURL('image/png')
  .replace('image/png', 'image/octet-stream');

link.click();