zoukankan      html  css  js  c++  java
  • 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,
                    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,
                    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();
                });
            })
    
  • 相关阅读:
    剑指offer-二维数组中的查找
    TF-IDF(term frequency–inverse document frequency)
    Java实现中文字符串的排序功能
    当前课程
    【R】资源整理
    CentOS相关
    【转】Setting up SDL Extension Libraries on MinGW
    【转】Setting up SDL Extension Libraries on Visual Studio 2010 Ultimate
    【转】Setting up SDL Extension Libraries on Code::Blocks 12.11
    【转】Setting up SDL Extension Libraries on Visual Studio 2019 Community
  • 原文地址:https://www.cnblogs.com/stt-bky/p/9518591.html
Copyright © 2011-2022 走看看