前言
图片是最常见的静态资源文件,可以从本地、外链获取图片,或者使用base64码展示。而canvas的toDataUrl() API可以将图片转base64码,然后模拟点击事件即可下载图片。
外链下载
在本地或者网站下载外链url图片时涉及到跨域,跨域会暴露自己的隐私,浏览器对跨域请求进行了限制,故需要设置crossOrigin为anonymous来允许跨域,浏览器会为这张图片的请求头附带Origin信息,告诉静态资源服务器,请在响应头中附带Access-Control-Allow-Methods、Access-Control-Allow-Origin,以便浏览器放行。
代码示例如下
eventEmitter.js
/* * 事件触发器 * @Author: wujiang * @Date: 2018-11-11 22:50:43 * @Last Modified by: wujiang * @Last Modified time: 2018-11-11 23:39:40 */ const EventEmitter = require('events') class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter() export default myEmitter
backend.js
import eventEmitter from './common/eventEmitter' // 图片下载对象 let downloadedImg = null // 待下载文件名 let fileName = null // 监听是否获取图片地址 eventEmitter.addListener('getHref',href => { imatateDownloadByA(href,fileName) }) /** * base64下载图片(可跨域) * @param {*} img * @param {String} filename 文件名 */ function downloadImg (imgUrl,filename) { fileName = filename startDownloadImg(imgUrl,getImgDataUrl) } /** * 开始下载图片之前 * @param {String} imgUrl * @param {Function} callback */ function startDownloadImg (imgUrl,callback) { let imageURL = imgUrl downloadedImg = new Image() downloadedImg.crossOrigin = 'Anonymous' downloadedImg.src = imageURL downloadedImg.addEventListener('load',callback,false) } /** * 获取图片下载base64字符串 * @param {DOMimg} domimg */ function getImgDataUrl () { const canvas = document.createElement('canvas') const context = canvas.getContext('2d') const width = downloadedImg.width || downloadedImg.naturalWidth const height = downloadedImg.height || downloadedImg.naturalHeight const imgSrc = downloadedImg.src let type = imgSrc.substring(imgSrc.lastIndexOf('.') + 1) let dtype = type === 'jpg' ? 'jpeg' : 'png' canvas.width = width canvas.height = height context.drawImage(downloadedImg,0) eventEmitter.emit('getHref',canvas.toDataURL(`image/${dtype}`)) } /** * 通过a标签模拟下载 * @param {String} href * @param {String} filename */ function imatateDownloadByA (href,filename) { const a = document.createElement('a') a.download = filename a.style.display = 'none' a.href = href document.body.appendChild(a) a.click() a.remove() window.URL.revokeObjectURL(href) } downloadImg('https://img.alicdn.com/imgextra/i2/54199406/O1CN012JLzreAxzn1xhNP_!!54199406.jpg','测试')
注意
原文链接:https://www.f2er.com/js/526373.html