import html2canvas from "html2canvas";
htmlToImg(str) {
if (this.isSavingImg) {
return false;
}
let zoom = 2.5;// Adjust the sharpness, the larger the clearer, 2.5 is a suitable value
let elem = document.querySelector(str);
var scale = zoom; //this.scale;
var width = $(elem).width();
var height = $(elem).height();
var canvas = document.createElement("canvas");
canvas.width = width * scale;
canvas.height = height * scale;
var context = canvas.getContext("2d");
[Important] Disable anti-aliasing
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
/ / context. Scale (0.5, 0.5);
context.scale(zoom, zoom);
// var context = canvas.getContext("2d");
var opts = {
// dpi: window.devicePixelRatio * scale,
scale: 1.//window.devicePixelRatio,
canvas: canvas, // Custom canvas
logging: false.// Log switch, easy to view html2Canvas internal execution process
/ / width: s: this. Sh,. / / the window screen. AvailHeight, / / dom original width
width: width,
height: height,
// x: 0,
// y: window.pageYOffset,
useCORS: true [Major] Enable cross-domain configuration
};
// $(".item-char").addClass("mt20");
try {
this.isSavingImg = true;
$.toast("Picture saved, please wait...");
html2canvas(elem, opts).then(canvas= >{$(".item-char").removeClass("mt20");
var imgUri = canvas.toDataURL("image/jpeg");
// this.uploadImage(this.dataURLtoBlob(imgUri));
this.uploadToSth(this.dataURLtoBlob(imgUri));
/* var fd = new FormData(); var file = new File([blob], "year2020.png"); fd.append("file", file); * /
});
} catch (e) {
this.isSavingImg = false; }}dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
// mime = arr[0].match(/:(.*?) ; / [1]),
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: "image/png" });
}
Copy the code