最近因为公司业务要求,须要完成一个一键生成照片图片打印总图的功能
html2canvas是一个很是强大的截图插件,不少生成图片和打印的场景会用到它
可是效果很模糊 ,本文主要记录一下若是解决模糊的问题以及各类参数如何设置html
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元素的宽高web
var context = canvas.getContext('2d');
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
复制代码
这段代码去除锯齿,会使图片变得清晰,结合scale放大处理canvas
若是生成的base64太大,会损耗性能,须要压缩base64promise
首先可能须要获取base64的大小bash
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
压缩的代码以下dom
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的一下处理ui