html2canvas截取div內容下載解決圖片模糊和圖片偏移

$("#btnsave").click(function(){html

    var copyDom = $("#modalcontent");canvas

    var width = copyDom.offsetWidth;//dom寬app

    var height = copyDom.offsetHeight;//dom高dom

    var scale = 2;//放大倍數url

    var canvas = document.createElement('canvas');spa

    canvas.width = width*scale;//canvas寬度code

    canvas.height = height*scale;//canvas高度htm

    var content = canvas.getContext("2d");圖片

    content.scale(scale,scale);ci

    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是按比例增長像素

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

    });

})

相關文章
相關標籤/搜索