1,默认生成的 canvas 图片在 retina 设备上显示很模糊,处理成 2 倍图能解决这个问题
var w = $("#code").width();
var h = $("#code").height();//要将 canvas 的宽高设置成容器宽高的 2 倍
var canvas = document.createElement("canvas");
canvas.width = w * 2;
canvas.height = h * 2;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
var context = canvas.getContext("2d");//然后将画布缩放,将图像放大两倍画到画布上
context.scale(2,2);
html2canvas(document.querySelector("#code"), { canvas: canvas, onrendered: function(canvas) { ... } });
2,js代码结构
var str = $('#html2canvas');
//console.log(str);
html2canvas([str.get(0)], {
onrendered: function (canvas) {
var image = canvas.toDataURL("image/png");
var pHtml = "<img src="+image+" />";
$('#html2canvas').html(pHtml);
}
});