a標籤點擊瀏覽器下載圖片,不打開

網上好多給a標籤加download屬性的,但都很差使。css

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>

	<style type="text/css">
		.box{border: 1px solid black;padding:0 10px;}
		img{width:200px;}
	</style>
	</head>
	<body>
		
    <!--建立一個cavas  用來存放圖片
        <canvas  id="cavasimg" width="607" height="367"  ></canvas> -->
		<img src="timg.jpg" id="cavasimg">
        
	<!--聲明一個按鈕  用來觸發下載圖片到本地-->
        <input type="button" id="btnsavaImg" value="保存圖片到本地" onclick="downloadIamge('img','timg.jpg')"/>   

<script>
// 調用方式
// 參數一: 選擇器,表明img標籤
// 參數二: 圖片名稱,可選
function downloadIamge(selector, name) {
    var image = new Image()
    // 解決跨域 Canvas 污染問題 解決跨域問題-並很差使,須要改對應的請求服務器
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
		var canvas = document.createElement('canvas')
		canvas.width = image.width
		canvas.height = image.height

		var context = canvas.getContext('2d')
		context.drawImage(image, 0, 0, image.width, image.height)
		var url = canvas.toDataURL('image/png')

		// 生成一個a元素
		var a = document.createElement('a')
		// 建立一個單擊事件
		var event = new MouseEvent('click')

		// 將a的download屬性設置爲咱們想要下載的圖片名稱,若name不存在則使用‘下載圖片名稱’做爲默認名稱
		a.download = name || '下載圖片名稱'
		// 將生成的URL設置爲a.href屬性
		a.href = url

		// 觸發a的單擊事件
		a.dispatchEvent(event)
	}

	image.src = document.querySelector(selector).src
}

</script>
	</body>

效果圖:
html

注意須要在tomcat或其它服務器上運行才能下載,直接在瀏覽器訪問html不能下載。
參考網址https://www.cnblogs.com/zhangkaiqiang/p/8183926.htmlcanvas

相關文章
相關標籤/搜索