html2canvas截取div内容下载解决图片模糊和图片偏移
$("#btnsave").click(function(){
var copyDom = $("#modalcontent");
var width = copyDom.offsetWidth;//dom宽
var height = copyDom.offsetHeight;//dom高
var scale = 2;//放大倍数
var canvas = document.createElement('canvas');
canvas.width = width*scale;//canvas宽度
canvas.height = height*scale;//canvas高度
var content = canvas.getContext("2d");
content.scale(scale,scale);
var rect = copyDom.get(0).getBoundingClientRect();//获取元素相对于视察的偏移量
content.translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位
html2canvas(copyDom[0], {
dpi: window.devicePixelRatio*2,
scale:scale,
canvas:canvas,
width:width,
heigth:height,
}).then(function (canvas) {
var url = canvas.toDataURL();
var triggerDownload = $("<a>").attr("href", url).attr("download", "详情.png").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
});
})
用的是2018 年8月22号在官网上下载的html2canvas.js代码。上述代码可以解决图片模糊和偏移的问题。
另外还有一种方法,设置配置即可,不存在图片偏移的问题,需要下载新版本,老版本的js不能用。
dpi: window.devicePixelRatio,scale:2,这两个配置 DPI是指每英寸的像素,scale是按比例增加像素
$("#btnsave").click(function(){
var copyDom = $("#modalcontent");
var width = copyDom.offsetWidth;//dom宽
var height = copyDom.offsetHeight;//dom高
var scale = 2;//放大倍数
html2canvas(copyDom[0], {
dpi: window.devicePixelRatio*2,
scale:scale,
width:width,
heigth:height,
}).then(function (canvas) {
var url = canvas.toDataURL();
var triggerDownload = $("<a>").attr("href", url).attr("download", "详情.png").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
});
})