<div id="qrcode" class="qrcode"></div>
import QRCode from "qrcodejs2";
export default {
data() {
return {
fs: 16,
border: 30,
width: 200,
height: 200,
canvasId: "qrcodeCanvas",
};
},
methods: {
genQrcode(content, bottomText, topText, qrcodeDom = null) {
document.getElementById(qrcodeDom).innerHTML = null;
const qrcodeContent = document.getElementById(qrcodeDom);
qrcodeContent.width = this.width + "px";
qrcodeContent.height = this.width + "px";
const qrcodeCanvas = new QRCode(qrcodeContent, {
text: content,
width: this.width,
height: this.height,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H,
});
let resolutionMultiple = 1;
let borderSize = this.border * resolutionMultiple;
let canvasWidth = this.width + this.border * 2 * resolutionMultiple;
let fontSize = this.fs * resolutionMultiple;
let canvasHeight = canvasWidth + fontSize * 3;
let canvas = document.createElement("canvas");
canvas.id = this.canvasId;
if (!canvas.getContext) return;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.drawImage(
qrcodeContent.querySelector("canvas"),
borderSize,
borderSize + this.border,
this.width,
this.height
);
ctx.fill();
ctx.fillStyle = "#666";
ctx.font = fontSize - 2 + "px Arial";
ctx.textAlign = "center";
if (bottomText) {
ctx = this.drawText(
ctx,
bottomText,
canvasWidth / 2,
this.width + borderSize + 40,
this.width
);
}
ctx.font = fontSize + "px Arial";
if (topText) {
ctx = this.drawText(ctx, topText, canvasWidth / 2, 10, this.width);
}
qrcodeContent.appendChild(canvas);
Array.from(qrcodeContent.childNodes).forEach((item) => {
if (!item.id) item.remove();
});
return qrcodeContent;
},
drawText(ctx, bottomText, x, y, w, space = 17) {
const chr = bottomText;
let temp = "";
const row = [];
for (let a = 0; a < chr.length; a++) {
if (
ctx.measureText(temp).width < w &&
ctx.measureText(temp + chr[a]).width <= w
) {
temp += chr[a];
} else {
row.push(temp);
temp = chr[a];
}
}
row.push(temp);
for (let b = 0; b < row.length; b++) {
ctx.fillText(row[b], x, y + (b + 1) * space);
}
return ctx;
},
download(name) {
const a = document.createElement("a");
a.href = document.getElementById(this.canvasId).toDataURL("image/png");
a.download = name;
a.click();
},
},
};
参考 https://www.cnblogs.com/qiushuiyu-108/p/17352350.html