$("#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();
});
})
