HTML元素转为图片并下载本地

发布于 2017-12-02  209 次阅读


利用了html2canvas讲Div转为Image

//Div转为Image 转后Img标签内Src为base64图片数据
function convertDivToImage() {
console.log($("#saveImg"));
html2canvas($("#saveImg"), {
allowTaint: true,
taintTest: false,
onrendered: function (canvas) {
canvas.id = "mycanvas";
//document.body.appendChild(canvas);
//生成base64图片数据
var dataUrl = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = dataUrl;
console.log(dataUrl);
// var canvas = convertImageToCanvas(image);
downloadFile('<%=Request["shopName"]%>.png', dataUrl);
}
});
}

function base64Img2Blob(code) {
var parts = code.split(';base64,');
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;

var uInt8Array = new Uint8Array(rawLength);

for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}

return new Blob([uInt8Array], { type: contentType });
}

function downloadFile(fileName, content) {
var aLink = document.createElement('a');
var blob = base64Img2Blob(content); //new Blob([content]);
 //构造FormData对象 以便传递到后台接收保存图片文件 然后返回图片Url
var formData = new FormData();
formData.append("filename", fileName); // 文件名
// JavaScript file-like 对象
formData.append("file", blob);
$.ajax({
url: 'ReceivePoster.ashx',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var a = document.createElement('a');//创建a标签
a.setAttribute('href', data);
a.setAttribute('download', fileName);
a.setAttribute("id", "downloadImg");
a.setAttribute("style", "display:none;");
var body = document.querySelector('body');
body.appendChild(a);
$("#downloadImg").click();
//因为有的浏览器不让弹窗,所以直接修改地址为图片URL
window.location.href = data; 
},
error: function (err) {
console.log(err);
}
});
}


LoneKing