最近因爲公司業務要求,須要完成一個一鍵生成照片圖片打印總圖的功能
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