初始版本提交

This commit is contained in:
yaoyn
2024-02-05 09:15:37 +08:00
parent b52d4414be
commit 445292105f
1848 changed files with 236859 additions and 75 deletions

View File

@ -0,0 +1,5 @@
import { withInstall } from '/@/utils';
import qrCode from './src/Qrcode.vue';
export const QrCode = withInstall(qrCode);
export * from './src/typing';

View File

@ -0,0 +1,112 @@
<template>
<div>
<component :is="tag" ref="wrapRef" />
</div>
</template>
<script lang="ts">
import { defineComponent, watch, PropType, ref, unref, onMounted } from 'vue';
import { toCanvas, QRCodeRenderersOptions, LogoType } from './qrcodePlus';
import { toDataURL } from 'qrcode';
import { downloadByUrl } from '/@/utils/file/download';
import { QrcodeDoneEventParams } from './typing';
export default defineComponent({
name: 'QrCode',
props: {
value: {
type: [String, Array] as PropType<string | any[]>,
default: null,
},
// 参数
options: {
type: Object as PropType<QRCodeRenderersOptions>,
default: null,
},
// 宽度
width: {
type: Number as PropType<number>,
default: 200,
},
// 中间logo图标
logo: {
type: [String, Object] as PropType<Partial<LogoType> | string>,
default: '',
},
// img 不支持内嵌logo
tag: {
type: String as PropType<'canvas' | 'img'>,
default: 'canvas',
validator: (v: string) => ['canvas', 'img'].includes(v),
},
},
emits: { done: (data: QrcodeDoneEventParams) => !!data, error: (error: any) => !!error },
setup(props, { emit }) {
const wrapRef = ref<HTMLCanvasElement | HTMLImageElement | null>(null);
async function createQrcode() {
try {
const { tag, value, options = {}, width, logo } = props;
const renderValue = String(value);
const wrapEl = unref(wrapRef);
if (!wrapEl) return;
if (tag === 'canvas') {
const url: string = await toCanvas({
canvas: wrapEl,
width,
logo: logo as any,
content: renderValue,
options: options || {},
});
emit('done', { url, ctx: (wrapEl as HTMLCanvasElement).getContext('2d') });
return;
}
if (tag === 'img') {
const url = await toDataURL(renderValue, {
errorCorrectionLevel: 'H',
width,
...options,
});
(unref(wrapRef) as HTMLImageElement).src = url;
emit('done', { url });
}
} catch (error) {
emit('error', error);
}
}
/**
* file download
*/
function download(fileName?: string) {
let url = '';
const wrapEl = unref(wrapRef);
if (wrapEl instanceof HTMLCanvasElement) {
url = wrapEl.toDataURL();
} else if (wrapEl instanceof HTMLImageElement) {
url = wrapEl.src;
}
if (!url) return;
downloadByUrl({
url,
fileName,
});
}
onMounted(createQrcode);
// 监听参数变化重新生成二维码
watch(
props,
() => {
createQrcode();
},
{
deep: true,
},
);
return { wrapRef, download };
},
});
</script>

View File

@ -0,0 +1,37 @@
import { toCanvas } from 'qrcode';
import type { QRCodeRenderersOptions } from 'qrcode';
import { RenderQrCodeParams, ContentType } from './typing';
import { cloneDeep } from 'lodash-es';
export const renderQrCode = ({
canvas,
content,
width = 0,
options: params = {},
}: RenderQrCodeParams) => {
const options = cloneDeep(params);
// 容错率,默认对内容少的二维码采用高容错率,内容多的二维码采用低容错率
options.errorCorrectionLevel = options.errorCorrectionLevel || getErrorCorrectionLevel(content);
return getOriginWidth(content, options).then((_width: number) => {
options.scale = width === 0 ? undefined : (width / _width) * 4;
return toCanvas(canvas, content, options);
});
};
// 得到原QrCode的大小以便缩放得到正确的QrCode大小
function getOriginWidth(content: ContentType, options: QRCodeRenderersOptions) {
const _canvas = document.createElement('canvas');
return toCanvas(_canvas, content, options).then(() => _canvas.width);
}
// 对于内容少的QrCode增大容错率
function getErrorCorrectionLevel(content: ContentType) {
if (content.length > 36) {
return 'M';
} else if (content.length > 16) {
return 'Q';
} else {
return 'H';
}
}

View File

@ -0,0 +1,88 @@
import { isString } from '/@/utils/is';
import { RenderQrCodeParams, LogoType } from './typing';
export const drawLogo = ({ canvas, logo }: RenderQrCodeParams) => {
if (!logo) {
return new Promise((resolve) => {
resolve((canvas as HTMLCanvasElement).toDataURL());
});
}
const canvasWidth = (canvas as HTMLCanvasElement).width;
const {
logoSize = 0.15,
bgColor = '#ffffff',
borderSize = 0.05,
crossOrigin,
borderRadius = 8,
logoRadius = 0,
} = logo as LogoType;
const logoSrc: string = isString(logo) ? logo : logo.src;
const logoWidth = canvasWidth * logoSize;
const logoXY = (canvasWidth * (1 - logoSize)) / 2;
const logoBgWidth = canvasWidth * (logoSize + borderSize);
const logoBgXY = (canvasWidth * (1 - logoSize - borderSize)) / 2;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// logo 底色
canvasRoundRect(ctx)(logoBgXY, logoBgXY, logoBgWidth, logoBgWidth, borderRadius);
ctx.fillStyle = bgColor;
ctx.fill();
// logo
const image = new Image();
if (crossOrigin || logoRadius) {
image.setAttribute('crossOrigin', crossOrigin || 'anonymous');
}
image.src = logoSrc;
// 使用image绘制可以避免某些跨域情况
const drawLogoWithImage = (image: CanvasImageSource) => {
ctx.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
};
// 使用canvas绘制以获得更多的功能
const drawLogoWithCanvas = (image: HTMLImageElement) => {
const canvasImage = document.createElement('canvas');
canvasImage.width = logoXY + logoWidth;
canvasImage.height = logoXY + logoWidth;
const imageCanvas = canvasImage.getContext('2d');
if (!imageCanvas || !ctx) return;
imageCanvas.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
canvasRoundRect(ctx)(logoXY, logoXY, logoWidth, logoWidth, logoRadius);
if (!ctx) return;
const fillStyle = ctx.createPattern(canvasImage, 'no-repeat');
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
};
// 将 logo绘制到 canvas上
return new Promise((resolve) => {
image.onload = () => {
logoRadius ? drawLogoWithCanvas(image) : drawLogoWithImage(image);
resolve((canvas as HTMLCanvasElement).toDataURL());
};
});
};
// copy来的方法用于绘制圆角
function canvasRoundRect(ctx: CanvasRenderingContext2D) {
return (x: number, y: number, w: number, h: number, r: number) => {
const minSize = Math.min(w, h);
if (r > minSize / 2) {
r = minSize / 2;
}
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
return ctx;
};
}

View File

@ -0,0 +1,4 @@
// 参考 qr-code-with-logo 进行ts版本修改
import { toCanvas } from './toCanvas';
export * from './typing';
export { toCanvas };

View File

@ -0,0 +1,10 @@
import { renderQrCode } from './drawCanvas';
import { drawLogo } from './drawLogo';
import { RenderQrCodeParams } from './typing';
export const toCanvas = (options: RenderQrCodeParams) => {
return renderQrCode(options)
.then(() => {
return options;
})
.then(drawLogo) as Promise<string>;
};

View File

@ -0,0 +1,38 @@
import type { QRCodeSegment, QRCodeRenderersOptions } from 'qrcode';
export type ContentType = string | QRCodeSegment[];
export type { QRCodeRenderersOptions };
export type LogoType = {
src: string;
logoSize: number;
borderColor: string;
bgColor: string;
borderSize: number;
crossOrigin: string;
borderRadius: number;
logoRadius: number;
};
export interface RenderQrCodeParams {
canvas: any;
content: ContentType;
width?: number;
options?: QRCodeRenderersOptions;
logo?: LogoType | string;
image?: HTMLImageElement;
downloadName?: string;
download?: boolean | Fn;
}
export type ToCanvasFn = (options: RenderQrCodeParams) => Promise<unknown>;
export interface QrCodeActionType {
download: (fileName?: string) => void;
}
export interface QrcodeDoneEventParams {
url: string;
ctx?: CanvasRenderingContext2D | null;
}