The down attribute in the a tag HTML5 the new property, which instructs the browser to download the URL instead of navigating to the URL, prompting the user to save it as a local file. Currently, this property has the following compatibility:
Specific code implementation:
1 /*2 main principle: Using the download attribute of a tag and the Todataurl () of the canvas3 selector: A selector for pictures4 Name: The name of the downloaded picture5 */6 downloadpicture (Selector, name) {7Let image =NewImage ()8 //solve cross-domain Canvas pollution issues9Image.setattribute (' Crossorigin ', ' anonymous ')TenImage.onload =function () { One //Create a canvas label ALet canvas = document.createelement (' Canvas ') - //set the canvas's width height -Canvas.width =Image.width theCanvas.height =Image.height - //Get Canvas's 2d interface -Let context = Canvas.getcontext (' 2d ') - //draw the picture on the canvas +Context.drawimage (image, 0, 0, 200, 200) - //Convert canvas content to base64 format +Let URL = Canvas.todataurl (' image/png ') A at //generate a element of a -Let A = document.createelement (' A ') - //Create a Click event -Let event =NewMouseEvent (' click ') - - //set the Download property of a to the name of the image we want to download, and use ' Download picture name ' as the default name if name does not exist inA.download = Name | | ' Download image name ' - //set the generated URL to the A.href property toA.href =URL + - //trigger A's Click event the a.dispatchevent (Event) * } $ //gets the SRC value on the IMG, after the assignment, the onload event is called after completionPanax NotoginsengIMAGE.SRC =Document.queryselector (selector). SRC -}
HTML5 a tag's down attribute for picture download