<template>
<canvas id="canvas" width="300" height="400"></canvas>
<el-button
style="margin-top: 20px"
type="danger"
plain
@click="downloadCode"
>下载二维码</el-button>
<div id="qrCode" style="display: none">
<el-row>
<qrcode-vue style="margin-left: 15%" :value="qrCodeUrl" :size="200"></qrcode-vue>
</el-row>
<el-row>
<el-button
style="margin-left: 50px; margin-top: 20px"
type="danger"
plain
@click="downloadCode"
>下载二维码</el-button>
</el-row>
</div>
</template>
<script name="qrcodeInfo" setup>
const props = defineProps({
// 二维码地址
qrCodeUrl: {
type: String,
default: "",
},
gunCode: {
type: String,
default: "",
}
})
import QrcodeVue from 'qrcode.vue'
import {getCurrentInstance, ref} from "vue";
import posterImg from '@/assets/images/qrCodeBack.png'
const { proxy } = getCurrentInstance();
// const qrCodeUrl = ref("");
defineExpose({
generateQRCode
})
async function generateQRCode() {
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d')
//清空画布
context.clearRect(0, 0, canvas.width, canvas.height);
const image = new Image();
image.src = posterImg;
image.crossOrigin = 'Anonymous';
// 等待图片加载完成
await new Promise((resolve) => {
image.onload = resolve;
});
// 绘制图片
context.drawImage(image, 0, 0, canvas.width, canvas.height);
// 生成二维码
//获取canvas标签
let qrCode = document.getElementById('qrCode').getElementsByTagName('canvas')
//创建a标签
let a = document.createElement('a')
const qrCodeDataUrl = await qrCode[0].toDataURL('img/png');
// 加载二维码图片
const qrCodeImage = new Image();
qrCodeImage.src = qrCodeDataUrl;
// 等待二维码图片加载完成
await new Promise((resolve) => {
qrCodeImage.onload = resolve;
});
// 绘制二维码图片 x,y,宽,高
context.drawImage(qrCodeImage, 55, 120, 190, 190);
//绘制文字
context.fillStyle = '#fff';
context.font = '30px Arial';
//传入显示的文本 x,y
context.fillText('NO:' + props.gunCode, 20, 380);
}
function downloadCode() {
const canvas = document.getElementById('canvas');
const downloadLink = document.createElement('a');
downloadLink.href = canvas.toDataURL('image/png');
downloadLink.download = props.gunCode + '.png';
downloadLink.click();
}
</script>
标签:canvas,vue,const,image,二维码,context,vue3,document
From: https://blog.51cto.com/momo1226/9179514