biji/前端/前端通过页面(dom)生成图片并放大倍数.md
2020-02-11 14:18:07 +08:00

1.4 KiB
Raw Blame History

代码

var canvas2 = document.createElement("canvas");
var _canvas = document.getElementById('app');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍然后盛放在较小的容器内就显得不模糊了
var times = 3;
canvas2.width = w * times  * window.devicePixelRatio;
canvas2.height = h * times  * window.devicePixelRatio;
canvas2.style.width = w + "px";
canvas2.style.height =h + "px";
var context = canvas2.getContext("2d");
context.scale(times, times);
console.log(canvas2.style.width)
    new html2canvas(document.getElementById('app'), {
        canvas:canvas2,
        allowTaint: true,
        taintTest: true,
        useCORS: true,
        background: null,
        windowWidth:document.body.scrollWidth,
        windowHeight:document.body.scrollHeight,
        x:0,
        y:0
    }).then(canvas => {
        let imgUrl = `<img style="width:100%" src="${canvas.toDataURL()}" />`
            doinghide()
            $('#app').replaceWith('<div id="app"></div>')
            $('#app').css('padding',0)
            $('#app').append(imgUrl)
    });
    }
})

html2canvas参数参考官网 重点介绍canvas那一部分 context.scale(x 倍数, y 倍数); //画板放大指定倍数


重点 canvas2.width = w * times * window.devicePixelRatio; //指定画板宽度 canvas2.height = h * times * window.devicePixelRatio; //指定画板宽度