97 lines
3.1 KiB
Plaintext
97 lines
3.1 KiB
Plaintext
|
|
import { QRCode } from './qrcode.min.js';
|
|
|
|
export type QrOpt = {
|
|
content:string,
|
|
logo?:string,
|
|
qrSize?:number,
|
|
logoW?:number,
|
|
logoH?:number,
|
|
marign?:number,
|
|
callback:(data:string)=>void
|
|
}
|
|
|
|
export const getQrData = async function (opt:QrOpt){
|
|
console.log(opt.content)
|
|
if(opt.qrSize==null){
|
|
opt.qrSize=300;
|
|
}
|
|
|
|
if(opt.marign==null){
|
|
opt.marign=1;
|
|
}
|
|
// 要生成的二维码内容
|
|
// var qrContent = "https://www.example.com";
|
|
|
|
//使用QRCode.toDataURL()方法生成base64字符串
|
|
// QRCode.toDataURL(opt.content, {
|
|
// //errorCorrectionLevel: QRCode.CorrectLevel.H, // 容错级别
|
|
// margin: 1, // 边距
|
|
// width: opt.qrSize!, // 二维码宽度
|
|
// height: opt.qrSize!, // 二维码高度
|
|
// color: {
|
|
// dark: "#000000", // 前景色(二维码颜色)
|
|
// light: "#ffffff" // 背景色(空白区域颜色)
|
|
// }
|
|
// }).then(function(base64) {
|
|
// // 在这里,base64是包含二维码图片的base64字符串
|
|
// // console.log(base64);
|
|
// opt.callback(base64);
|
|
// // return base64;
|
|
// // 你可以将base64字符串设置为img元素的src属性来显示二维码
|
|
// // var img = document.createElement('img');
|
|
// // img.src = base64;
|
|
// // document.body.appendChild(img);
|
|
|
|
// // 你也可以将base64字符串用于其他目的,比如下载或传输
|
|
// }).catch(function(error) {
|
|
// console.error("生成二维码时出错:", error);
|
|
// });
|
|
|
|
//return "";
|
|
|
|
|
|
const qrcodeCanvas = document.createElement('canvas');
|
|
qrcodeCanvas.width = opt.qrSize!;
|
|
qrcodeCanvas.height = opt.qrSize!;
|
|
|
|
// 使用QRCode对象生成二维码
|
|
await QRCode.toCanvas(qrcodeCanvas, opt.content, { width: opt.qrSize!,height: opt.qrSize!,margin: opt.marign!}, (error) => {
|
|
if (error) console.error(error);
|
|
});
|
|
if(opt.logo==null){
|
|
opt.callback(qrcodeCanvas.toDataURL('image/png'))
|
|
return;
|
|
}
|
|
|
|
// 获取logo图片
|
|
const logoImage = new Image();
|
|
logoImage.src = opt.logo!; // 替换为你的logo图片路径
|
|
logoImage.onload = () => {
|
|
// 创建一个用于合成带有logo的二维码的canvas元素
|
|
const logoQRCodeCanvas = document.createElement('canvas');
|
|
logoQRCodeCanvas.width = qrcodeCanvas.width;
|
|
logoQRCodeCanvas.height = qrcodeCanvas.height;
|
|
const ctx = logoQRCodeCanvas.getContext('2d');
|
|
|
|
// 将基本的二维码绘制到新的canvas上
|
|
ctx.drawImage(qrcodeCanvas, 0, 0);
|
|
|
|
// 计算logo的大小和位置
|
|
const logoSize = opt.logoW!; // logo的显示大小
|
|
const logoX = (logoQRCodeCanvas.width - opt.logoW!) / 2;
|
|
const logoY = (logoQRCodeCanvas.height - opt.logoH!) / 2;
|
|
|
|
// 在二维码上绘制logo
|
|
ctx.drawImage(logoImage, logoX, logoY, logoSize, opt.logoH);
|
|
|
|
// 将带有logo的二维码canvas转换为base64图片
|
|
const base64Image = logoQRCodeCanvas.toDataURL('image/png');
|
|
|
|
// 将base64图片存储到组件的数据中
|
|
// this.qrcodeWithLogo = base64Image;
|
|
opt.callback(base64Image)
|
|
};
|
|
|
|
|
|
} |