[javascript] Download image with JavaScript

Right now I have a canvas and I want to save it as PNG. I can do it with all those fancy complicated file system API, but I don't really like them.

I know if there is a link with download attribute on it:

<a href="img.png" download="output.png">Download</a>

it will download the file if the user clicks on it. Therefore I came up with this:

$("<a>")
    .attr("href", "img.png")
    .attr("download", "output.png")
    .appendTo("body")
    .click()
    .remove();

Demo: http://jsfiddle.net/DerekL/Wx7wn/

However, it doesn't seem to work. Does it have to be trigger by an user action? Or else why didn't it work?

This question is related to javascript jquery download

The answer is


As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to download

how to download file in react js How do I download a file with Angular2 or greater Unknown URL content://downloads/my_downloads python save image from url How to download a file using a Java REST service and a data stream How to download file in swift? Where can I download Eclipse Android bundle? How to download image from url android download pdf from url then open it with a pdf reader Flask Download a File