html2canvas保存图片压缩图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
async $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)
}
}