原生JS方法
引入html2canvas
http://html2canvas.hertzen.com/dist/html2canvas.min.js
html代码部分
html2canvas*{
margin: 0;
padding: 0;
}
#htmlcanvas{
padding: 10px;
background: red;
height: 300px;
}
#ddd{
width: 100px;
height: 100px;
}
html内容
那一瞬间有一百万可能
canvas内容
保存
JS部分
var img = "https://qiniuimage.shengyaapp.com//H5/image/SQJZ/admin/listBtn.png";//imgurl 就是你的图片路径
function getBase64(imgUrl) {
return new Promise((resolve) => {
setTimeout(() => {
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", imgUrl, true);
// 至关重要
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
//得到一个blob对象
var blob = this.response;
console.log("blob", blob)
// 至关重要
let oFileReader = new FileReader();
oFileReader.onloadend = function (e) {
let base64 = e.target.result;
document.getElementById("ddd").src = base64
html2canvas(document.querySelector("#htmlcanvas")).then(canvas => {
document.getElementById("canid").appendChild(canvas);
canvas.style.display = 'none';
});
console.log(document.getElementById("ddd").src)
};
oFileReader.readAsDataURL(blob);
}
}
xhr.send();
resolve()
}, 100);
})
}
document.getElementById("btn").onclick = function(){
getBase64(img).then(function(){
return xiazai()
})
}
function xiazai(){
return new Promise((resolve) => {
setTimeout(() => {
var strDataURI11;
var canv = document.getElementsByTagName("canvas")[0]
canv.crossOrigin = "anonymous"
var strDataURI = canv.toDataURL();
strDataURI11 = strDataURI
var blob=new Blob([''], {type:'application/octet-stream'});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = strDataURI11;
a.download = strDataURI11.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
URL.revokeObjectURL(url);
document.getElementById("canid").innerHTML = ''
resolve()
},200);
})
}