坑1:图片不显示
产生原因:
图片未开启跨域
解决办法:
升级版本 html2canvas v1.0.0-alpha.1
及以上,解决方案代码如下
var str = document.getElementById('#html2canvas');
html2canvas(str, {
useCORS: true, // 设置 useCORS 为 true,即可开启图片跨域
onrendered: function (canvas) {
var image = canvas.toDataURL("image/jpeg",1.0);
window.open(image);
}
});
坑2:清晰度
产生原因:
html2canvas 默认dpi为 72,在高分屏上被放大2倍以上,导致图像失真
解决办法:
升级版本 html2canvas v1.0.0-alpha.1
及以上,解决方案代码如下
var str = document.getElementById('#html2canvas');
html2canvas(str, {
scale: 2, // 设置 scale 为 2 及以上,即可支持高分屏
onrendered: function (canvas) {
var image = canvas.toDataURL("image/jpeg",1.0);
window.open(image);
}
});
坑3:pdf 一片黑
产生原因:
html2canvas 默认背景色为黑色
解决办法:
升级版本 html2canvas v1.0.0-alpha.1
及以上,解决方案代码如下
var str = document.getElementById('#html2canvas');
html2canvas(str, {
background: '#FFFFFF', // 默认为黑色,将 background 为其他颜色
onrendered: function (canvas) {
var image = canvas.toDataURL("image/jpeg",1.0);
window.open(image);
}
});
坑2:长网页导出异常
产生原因:
base64 超过 500k,后置字符将丢失
解决办法:
升级版本 html2canvas v1.0.0-alpha.1
及以上,将网页拆分成几部分,解决方案代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PDF导出</title>
</head>
<body>
<button id="exportToPdf">导出为PDF</button>
<div id="html2canvas">
<div class="cls">
<p>1</p>
</div>
<div class="cls">
<p>2</p>
</div>
<div class="cls">
<p>3</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
<script src="https://rawgit.com/eKoopmans/html2canvas/develop/dist/html2canvas.min.js"></script>
<script>
var downPdf = document.getElementById("exportToPdf");
downPdf.onclick = function () {
var s = document.getElementsByClassName("cls");
var pdf = new jsPDF('', 'pt', 'a4');
var imgArr = new Array();
for (var index = 0; index < s.length; index++) {
html2canvas(s[index], {
useCORS: true,
scale: 2,
background: "#F5F5F5",
onrendered: function (canvas) {
var img = new Image();
img.width = canvas.width;
img.height = canvas.height;
img.src = canvas.toDataURL('image/jpeg', 1.0);
imgArr.push(img)
createPdf(pdf,imgArr,s.length);
},
})
};
}
var createPdf = function (pdf,Arr, s) {
if (Arr.length == s) {
for (var i = 0; i < Arr.length; i++) {
pdf.addImage(Arr[i].src, 'JPEG', 0, 0, Arr[i].width, Arr[i].height);
if(i < Arr.length -1){
pdf.addPage();
}
}
pdf.save("test.pdf")
}
}
</script>
</body>
</html>