vuejs如何利用qrcode生成二维码,下面编程教程网小编给大家详细介绍一下具体代码!
安装脚手架
npm i qrcode -S
npm install --save @types/qrcode
二维码组件介绍
<template>
<canvas id="canvas" ref="canvas" :width="width" :height="height"></canvas>
</template>
<script setup>
import QRCode from "qrcode";
import { onMounted, ref } from "vue";
const props = defineProps({
//二维码存储内容
qrUrl: {
type: String,
default: "Hello World"
},
// canvas width
width: {
type: Number,
default: 400
},
// canvas height
height: {
type: Number,
default: 400
},
// 二维码尺寸(正方形 长宽相同)
qrSize: {
type: Number,
default: 360
},
// 二维码底部文字
qrText: {
type: String,
default: "Hello World"
},
//底部说明文字字号
qrTextSize: {
type: Number,
default: 24
}
});
const qrCodeOption = {
errorCorrectionLevel: "H",
width: props.qrSize,
version: 7
};
const canvas = ref<HTMLCanvasElement>();
/**
* @argument qrUrl 二维码内容
* @argument qrSize 二维码大小
* @argument qrText 二维码中间显示文字
* @argument qrTextSize 二维码中间显示文字大小(默认16px)
*/
const handleQrcode = () => {
let dom = canvas.value as HTMLCanvasElement;
QRCode.toDataURL(props.qrUrl, qrCodeOption)
.then((url: string) => {
// 画二维码里的logo// 在canvas里进行拼接
const ctx = dom.getContext("2d") as CanvasRenderingContext2D;
const image = new Image();
image.src = url;
setTimeout(() => {
ctx.drawImage(image, (props.width - props.qrSize) / 2, 0, props.qrSize, props.qrSize);
if (props.qrText) {
//设置字体
ctx.font = "bold " + props.qrTextSize + "px Arial";
let tw = ctx.measureText(props.qrText).width; // 文字真实宽度
let ftop = props.qrSize - props.qrTextSize; // 根据字体大小计算文字top
let fleft = (props.width - tw) / 2; // 根据字体大小计算文字left
ctx.fillStyle = "#fff";
ctx.textBaseline = "top"; //设置绘制文本时的文本基线。
ctx.fillStyle = "#333";
ctx.fillText(props.qrText, fleft, ftop);
}
}, 0);
})
.catch((err: Error) => {
console.error(err);
});
};
onMounted(() => {
handleQrcode();
});
</script>
二维码下载
const savePic = () => {
let dom = canvas.value as HTMLCanvasElement;
let a = document.createElement("a");
//将二维码面板处理为图片
a.href = dom.toDataURL("image/png", 0.5);
a.download = props.qrUrl + ".png";
a.click();
};
defineExpose({ savePic });
以上是编程学习网小编为您介绍的“vuejs如何利用qrcode生成二维码”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
编程基础网
本文标题为:vuejs如何利用qrcode生成二维码
基础教程推荐
猜你喜欢
- php – 将html / css / js添加到mysql的最安全的方法是什么? 2023-10-26
- Vue实现计数器案例 2024-01-16
- HTML5实现自带进度条和滑块滑杆效果 2024-01-17
- vue cli3 + ts 打包之后,不显示页面 2023-10-08
- Flutter Tab 切换时保留tab的状态 2022-09-08
- 子Div使用Float后撑开父Div的几种方法 2024-01-08
- ajax实现修改功能 2023-02-01
- vue webpack重写cookie路径的方法 2024-02-10
- JS获取几种URL地址的方法小结 2023-12-14
- javascript 按键事件(兼容各浏览器) 2023-12-14
