序言
近期因为企业业务流程规定,必须进行1个1键转化成相片照片复印总图的作用
html2canvas是1个十分强劲的截图软件,许多转化成照片和复印的情景会用到它
可是实际效果很模糊不清 ,本文关键纪录1下假如处理模糊不清的难题和各种各样主要参数怎样设定
文件目录
基础用法
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的1下解决
以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。