js点击下载图片

src需要注意,不同源情况下图片有跨域情况,需要后台开放权限,如果是前端本地图片可以动态获取地址

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<a onclick="downCom()">下载图片</a>
		<img ref="imgaa" id="imgaa" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.duanlonglong.com%2Fuploads%2Fallimg%2F210609%2F1-2106091644394P.png&refer=http%3A%2F%2Fwww.duanlonglong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1645319184&t=6ec886be2d65e16599e03e88f36af984" >
		<!-- 如果是vue动态绑定img的src属性 绝对路径下 fatherList.imgSrc代表../../../image/tupian.png-->
		<!-- <img :src="require('' + fatherList.imgSrc)" alt="" ref="image" /> -->
	</body>
	<script type="text/javascript">
		function downCom() {
			// src需要注意,不同源情况下图片有跨域情况,需要后台开放权限,如果是前端本地图片可以动态获取地址 如:
			// vue下 let data = this.$refs.imgaa; let src = data.src;
			// vue与js下 document.querySelector("#imgaa").src;
			let src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.duanlonglong.com%2Fuploads%2Fallimg%2F210609%2F1-2106091644394P.png&refer=http%3A%2F%2Fwww.duanlonglong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1645319184&t=6ec886be2d65e16599e03e88f36af984';
			let name = '段龙龙博客图片1';
			// src为图片地址,name为下载后图片的命名
			this.downloadByBlob(src, name);
			debugger
		}

		function downloadByBlob(url, name) {
			let image = new Image()
			image.setAttribute('crossOrigin', 'anonymous')
			image.src = url
			image.onload = () => {
				let canvas = document.createElement('canvas')
				canvas.width = image.width
				canvas.height = image.height
				let ctx = canvas.getContext('2d')
				ctx.drawImage(image, 0, 0, image.width, image.height)
				canvas.toBlob((blob) => {
					let url = URL.createObjectURL(blob)
					download(url, name)
					// 用完释放URL对象
					URL.revokeObjectURL(url)
				})
			}
		}

		function download(href, name) {
			let eleLink = document.createElement('a')
			eleLink.download = name
			eleLink.href = href
			eleLink.click()
			eleLink.remove()
		}
	</script>
</html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.duanlonglong.com/qdjy/1250.html