html2canvas保存图片压缩图片 发表于 2017-12-05 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263async $html2canvas(el, options = {}) { const { type } = options; const canvas = await html2canvas(el, { useCORS: true }); try { if(type && type === "dataURL") { return canvas.toDataURL("image/png"); } else { console.warn("warn"); return canvas; } } catch(err) { console.log("err"); console.log(err); } return canvas;},async print() { const el = document.getElementById("invite"); var width = el.offsetWidth * 0.8; var height = el.offsetHeight * 0.8; const options = { type: "dataURL", useCORS: true, logging: true, taintTest: false, allowTaint: false, width: el.offsetWidth * 0.8, height: el.offsetHeight * 0.8 }; var output = await this.$html2canvas(el, options); this.ImgToBase64(output, width, height);},ImgToBase64(base64, width, height) { //压缩图片 var that = this; var img = new Image(); img.src = base64; img.onload = function() { var rate = 0.8; //压缩图片 img.width = width * rate; img.height = height * rate; //生成canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); var base64 = canvas.toDataURL('image/jpeg', 0.95); that.output = base64; that.$nextTick(() => { setTimeout(() => { that.$emit("savaImg", that.output); }, 0) }) console.log('that.output') console.log(that.output) }}