/**
* 下载图片到本地,可适用于移动端
*/
let urlVal = "https://avuejs.com/images/logo-bg.jpg";
let data = {
url: urlVal,
width: 300,
height: 300,
urlName: '图片名字',
}
downLoadImgByUrl(data)
const downLoadImgByUrl = ({url, width, height, urlName}) => {
let canvas = document.createElement('CANVAS')
let ctx = canvas.getContext('2d')
let img = new Image()
img.crossOrigin = 'Anonymous'
img.onload = function () {
let ResWidth
let ResHeight
if (width && height) {
ResWidth = width
ResHeight = height
} else if (width) {
ResWidth = width
ResHeight = img.height * (width / img.width)
} else if (height) {
ResHeight = height
ResWidth = img.width * (height / img.height)
} else {
ResWidth = img.width
ResHeight = img.height
}
canvas.width = ResWidth
canvas.height = ResHeight
console.log(ResWidth, ResHeight)
ctx.drawImage(img, 0, 0, ResWidth, ResHeight)
let saveA = document.createElement('a')
document.body.appendChild(saveA)
saveA.href = canvas.toDataURL('image/jpeg', 1)
saveA.download = urlName ? urlName : 'mypic' + new Date().getTime()
saveA.target = '_blank'
saveA.click()
canvas = null
}
img.src = url
}