html2canvas生成清晰的图片实现打印代码示例

作者:袖梨 2022-06-25

本篇文章小编给大家分享一下html2canvas生成清晰的图片实现打印代码示例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

基本用法

处理模糊问题

细节问题-压缩base64, 导出处理

基本用法

window.html2canvas(dom, {
        scale: scale,
        width: dom.offsetWidth,
        height: dom.offsetHeight
    }).then(function (canvas) {
        var context = canvas.getContext('2d');
        context.mozImageSmoothingEnabled = false;
        context.webkitImageSmoothingEnabled = false;
        context.msImageSmoothingEnabled = false;
        context.imageSmoothingEnabled = false;
        var src64 = canvas.toDataURL()
}

scale 为放大倍数 ,我这里设置为4 ,越高理论上越清晰

dom.offsetWidth height: dom.offsetHeight 直接取得需要转为图片的dom元素的宽高

处理模糊问题

var context = canvas.getContext('2d');
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;

这段代码去除锯齿,会使图片变得清晰,结合scale放大处理

细节问题

如果生成的base64太大,会损耗性能,需要压缩base64

首先可能需要获取base64的大小

getImgSize: function (str) {
    //获取base64图片大小,返回KB数字
    var str = str.replace('data:image/jpeg;base64,', '');//这里根据自己上传图片的格式进行相应修改

    var strLength = str.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);

    // 由字节转换为KB
    var size = "";
    size = (fileLength / 1024).toFixed(2);

    return parseInt(size);
}

然后根据获取的大小判断你是否要压缩base64

压缩的代码如下

compress: function (base64String, w, quality) {
    var getMimeType = function (urlData) {
        var arr = urlData.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        // return mime.replace("image/", "");
        return mime;
    };
    var newImage = new Image();
    var imgWidth, imgHeight;

    var promise = new Promise(function (resolve) {
        newImage.onload = resolve;
    });
    newImage.src = base64String;
    return promise.then(function () {


        imgWidth = newImage.width;
        imgHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = w * imgHeight / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = w * imgWidth / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        var base64 = canvas.toDataURL(getMimeType(base64String), quality);   
        return base64;
    })
}

使用方法

self.compress(src64,width,1).then(function(base){
    src64 = base
    src64 = src64.replace(/data:image/.*;base64,/, '')
    // 调用接口保存图片
}).catch(function(err){
    dialog.tip(err.message, dialog.MESSAGE.WARN);
})

本文主要包括,html2canvas使用,参数,如何保证图片的清晰度和base64的一下处理

相关文章

精彩推荐