Open chenjianou opened 3 years ago
function drawImage(src: string): Promise<string> { let image: HTMLImageElement = new Image, canvas: HTMLCanvasElement = document.createElement('canvas'), ctx = canvas.getContext('2d'); image.setAttribute('crossOrigin', 'Anonymous'); image.src = src; return new Promise((resolve) => { image.onload = () => { let { width, height } = image; canvas.width = width; canvas.height = height; ctx!.drawImage(image, 0, 0); canvas.toBlob((blob) => { let url = URL.createObjectURL(blob); resolve(url) }); } }) } function download(src: string, name?: string) { let a = document.createElement('a'); let realName: string = name || src; a.download = realName; document.body.appendChild(a) drawImage(src).then(url => { a.href = url; a.click(); URL.revokeObjectURL(url); }); } export { download }