a label - across domains - Download

Reason: The server address stored in the picture has been changed at
the phenomenon: a label do not use the downloaded image manipulation, it will directly open the preview
to solve:
first picture and then converted to base64 format during download, encapsulates the two methods, specifically to see the comments

Page code as
<Button @ click = downImg ( ' https: //xxx/xxx/xxx.png')> download </ the Button>
downImg (URL) {
const IMG = document.createElement ( 'IMG')
img.crossOrigin = 'Anonymous' // effects: cross-domain. Here we must note the following in order not to write, or will report canvas contaminated error
// namely: Uncaught DOMException: Failed to the Execute 'toDataURL' ON 'HTMLCanvasElement': Tainted BE Canvases May not exported.
Img.src url =
img. = the onload () => {
// turn retrieval method base64 package
const = dataBase64 getBase64Image (IMG)
// do a tag download process
clickDown (dataBase64, 'two-dimensional code')
}
}


======================== following packaging method
/ **
*
* A label disposed download
* @param
* The first parameter is downloaded address
* the second parameter is the name of the file after the download, do not pass the default empty
* @return Download
*
*
* * /
Export function clickDown (URL, name = '') {
const Link = document.createElement ( 'a')
URL = link.href
link.download name =
document.body.appendChild (Link)
link.click ()
document.body.removeChild (Link)
}

/**
*
* 将图片转为base64格式
* @param 图片对象
* @return base64字符串
*
* */
export function getBase64Image (img) {
if (!img) return
let canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
return canvas.toDataURL('image/' + ext)
}

Guess you like

Origin www.cnblogs.com/victory820/p/10936240.html