准备工作
// jq 页面必备 必须引入元素嘛
<script src="./jquery-3.4.1.min.js"></script>
// bluebird 其实用得比较经常 babel es6 转es5 的一个插件
<script src="./bluebird.js"></script>
// html2canvas 我们核心插件
<script src="./html2canvas.min.js"></script>
应用
- index.html
<body class="Body">
<div class="AllWrap relative">
<button
title="保存为图片"
style="position: absolute;top:30px;left:100px;"
onclick="saveCanvas()"
>
保 存
</button>
<a href="" download="下载图.png" id="download"></a>
</div>
</body
- 添加脚本
<script>
// 判断浏览器是否为IE 且为IE11以下
function isIE() {
if (!!window.ActiveXObject || 'ActiveXObject' in window) {
return true
} else {
return false
}
}
function saveCanvas() {
// html2canvas($('.Body')).then(function(canvas) {
// var imgUri = canvas
// .toDataURL('image/png')
// .replace('image/png', 'image/octet-stream')
// $('#download').attr('href', imgUri)
// console.log(imgUri)
// document.getElementById('download').click()
// })
html2canvas($('.Body'), {
allowTaint: true,
useCORS: true,
onrendered: function(canvas) {
if (isIE || isIE11 || isEdge) {
var blob = canvas.msToBlob()
navigator.msSaveBlob(blob, 'a.png')
return
}
console.log(123)
canvas.id = 'mycanvas'
var dataURL = canvas.toDataURL('image/png')
var mine_type = 'image/png'
var save_link = document.createElement('a')
save_link.setAttribute('download', 'img')
save_link.href = dataURL
var event = document.createEvent('MouseEvents')
event.initMouseEvent(
'click',
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
)
save_link.dispatchEvent(event)
}
})
}
</script>
其实这都很简单,琢磨一波 就阔以了
来源:CSDN
作者:你的贱已深入骨髓
链接:https://blog.csdn.net/zhan_lijian/article/details/103481248