Recently in the project, a function of downloading pictures is needed (as shown below)
At first consider using the DOWNLOAD attribute of the A tag to download:
<A HREF = Picture SRC DOWNLOAD = Download Poster> Download Poster </a>
However, after testing, I found that in Safari, the downloaded files cannot be brought to the expansion name, so I have to change my mind and use Canvas for processing.
1. Image need to add crossorigin = 'Anonymous' to set the cross -domain attribute of the image
img.crossorigin = 'Anonymous';
2. Use TodataURL to convert the picture to base64 format
Canvas.todataurl (Image/PNG)
3. Use analog click event to trigger download
var save_link = document.createElement ('A'); Save_link.href = Image; Save_link.download = 'Test .png'; VAR CLICKEVENT = DCUMENT.CREATEEVENT ('More Seevents'); FALSE); Save_link.dispatchevent (Clickevent);
Full code:
var canvas = $ ('. Canvas'); var cxt = canvas [0] .GetContext (2D); function save () {var IMG = New Image (); img.crossorigin = 'Anonymous'; img.on Load = FUNCTION () {var _w = img.naturalWidth; var _h = img.naturalHeight; canvas.attr ({width: _w, height: _h}); [0] .todataurl (Image/PNG) VAR SAVE_LINK = DOCUMENT.CREATEELEMENT ('A'); Save_link.href = Image; Save_link.download = 'Test .png'; cument.createevent ('mouseevents'); ('click', true, false); Save_link.dispatchevent (click);}; img.src = 'http://n.sinaimg.cn/transform/20170825/nzi3- fykiu Fe6650492.jpg ';}
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.