Search code examples
javascripthtmldownloadgifanimated-gif

How to download a GIF from a given URL using Javascript


I am trying to download a GIF from Giphy (just need to download it, I don't need to display it on the browser).

I tried using the solution in this question this question however it downloads a static image:

function download_img(e, link){
    var image = new Image();
    image.crossOrigin = "anonymous";
    image.src = link;
    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
        canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
        canvas.getContext('2d').drawImage(this, 0, 0);
        var blob;
        // ... get as Data URI
        if (image.src.indexOf(".jpg") > -1) {
            blob = canvas.toDataURL("image/jpeg");
        } else if (image.src.indexOf(".png") > -1) {
            blob = canvas.toDataURL("image/png");
        } else if (image.src.indexOf(".gif") > -1) {
            blob = canvas.toDataURL("image/gif");
        } else {
            blob = canvas.toDataURL("image/png");
        }
        tempbtn = document.createElement('a');
        tempbtn.href = blob;
        tempbtn.download = 'giphy.gif'; // or define your own name. 
        tempbtn.click();
        tempbtn.remove(); 
    };
}
<a href="#" onclick="download_img(this,'https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif')"  > Descargar gif </a>

I also wonder why it's needed to create a new Image(); and create a canvas tag


Solution

  • This works for me, I took some of the code from here https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/

    (async () => {
      //create new a element
      let a = document.createElement('a');
      // get image as blob
      let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
      let file = await response.blob();
      // use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
      a.download = 'myGif';
      a.href = window.URL.createObjectURL(file);
      //store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
      a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
      //click on element to start download
      a.click();
    })();