Drag Out Images and Canvas With Filenames

It can be annoying that when you drag out images of a browser window, they are named png.png (or something equally useless). I was playing around with fixing this - it is a little inconvenience in my CSS Sprite Generator that would be nice to have working (naming the file based on their input). Here is what I came up with (no library dependancies):

function dragoutImages() {
  if (!document.addEventListener) {
    return;
  }

  document.addEventListener("dragstart", function(e) {
    var element = e.target;
    var src;

    if (element.tagName === "IMG" && element.src.indexOf("data:") === ) {
      src = element.src;
    }

    if (element.tagName === "CANVAS") {
      try {
          src = element.toDataURL();
      }
      catch(e) {  }
    }

    if (src) {
      var name = element.getAttribute("alt") || "download";
      var mime = src.split(";")[].split("data:")[1];
      var ext = mime.split("/")[1] || "png";
      var download = mime + ":" + name + "." + ext + ":" + src;

      e.dataTransfer.setData("DownloadURL", download);
    }
  }, false);
}

You just need to specify the alt attribute on the image or canvas to specify your name (along with the draggable attribute on canvas elements) and the script should handle the rest.

Browser Support

I am not 100% sure on browser support. This used to be Chrome only according to this HTML5rocks article, but maybe other browsers have picked it up by now. It is a neat little addition when available though.

Demos

See the full demo: drag out images with custom file name. This shows the ability to drag out both image and canvas tags.

On this page, you should be able to drag out the following colorpicker screenshot, which will be called spectrum.png.

spectrum