小编给大家分享一下html2中canvas如何生成清晰的图片实现打印功能,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
创新互联公司从2013年创立,先为罗城等服务建站,罗城等地企业,进行企业商务咨询服务。为罗城企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
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的一下处理
看完了这篇文章,相信你对“html2中canvas如何生成清晰的图片实现打印功能”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!