最近由于公司業(yè)務(wù)要求,需要完成一個(gè)一鍵生成照片圖片打印總圖的功能
html2canvas是一個(gè)非常強(qiáng)大的截圖插件,很多生成圖片和打印的場(chǎng)景會(huì)用到它
但是效果很模糊 ,本文主要記錄一下如果解決模糊的問(wèn)題以及各種參數(shù)如何設(shè)置
基本用法
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 為放大倍數(shù) ,我這里設(shè)置為4 ,越高理論上越清晰
dom.offsetWidth height: dom.offsetHeight 直接取得需要轉(zhuǎn)為圖片的dom元素的寬高
處理模糊問(wèn)題
var context = canvas.getContext('2d');
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
這段代碼去除鋸齒,會(huì)使圖片變得清晰,結(jié)合scale放大處理
細(xì)節(jié)問(wèn)題
如果生成的base64太大,會(huì)損耗性能,需要壓縮base64
首先可能需要獲取base64的大小
getImgSize: function (str) {
//獲取base64圖片大小,返回KB數(shù)字
var str = str.replace('data:image/jpeg;base64,', '');//這里根據(jù)自己上傳圖片的格式進(jìn)行相應(yīng)修改
var strLength = str.length;
var fileLength = parseInt(strLength - (strLength / 8) * 2);
// 由字節(jié)轉(zhuǎn)換為KB
var size = "";
size = (fileLength / 1024).toFixed(2);
return parseInt(size);
}
然后根據(jù)獲取的大小判斷你是否要壓縮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,/, '')
// 調(diào)用接口保存圖片
}).catch(function(err){
dialog.tip(err.message, dialog.MESSAGE.WARN);
})
本文主要包括,html2canvas使用,參數(shù),如何保證圖片的清晰度和base64的一下處理
總結(jié)
以上所述是小編給大家介紹的html2 canvas生成清晰的圖片實(shí)現(xiàn)打印功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!