哎哟~ 你干嘛 —— 表情包都违规的吗
<template>
<div class="ikun">
<!-- <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
<canvas ref="canvas1" :width="canvasWidth1" :height="canvasHeight1"></canvas> -->
<input v-model="iKunName" class="ikun-input"/>
<img ref="img1" :src="imageData" alt="">
<button @click="downloadImg" class="ikun-btn">请下载iKun二维码合照</button>
<!-- 合成二维码所需的背景图 —— 勿删 ,由于本地获取其他环境的图片会出现跨域-->
<img class="ikun1" src="@/assets/ik/ikunxhz.jpg" style="display: none" />
<!-- <img class="ikun2" src="@/assets/ik/ikun2.gif" style="display: none" /> -->
</div>
</template>
<script>
import QRCode from 'qrcode'
export default {
data() {
return {
deptNameAll: [],
canvasWidth: 1000, // 画布宽度
canvasHeight: 600, // 画布高度
canvasWidth1: 340, // 二维码画布宽度
canvasHeight1: 340, // 二维码画布高度
imageUrl: `${location.origin}/csp/ipad%E4%BA%8C%E7%BB%B4%E7%A0%81%E8%83%8C%E6%99%AF.png`, // 图片URL
qrCodeText: 'https://cn.bing.com/', // 二维码文本
imageData: '',
iKunName: '哎哟~ 你干嘛~ iKun-小黑子!',
}
},
mounted() {
this.generateImage()
},
methods: {
downloadImg() {
this.imageUrl = document.querySelector('.ikun1')?.src
if (this.iKunName) {
this.generateImage()
} else {
return alert('下载失败,iKun 的名称不能为空空~!')
}
},
async generateImage() {
const canvas = document.createElement('canvas')
canvas.width = this.canvasWidth
canvas.height = this.canvasHeight
const canvas1 = document.createElement('canvas')
canvas1.width = this.canvasWidth1
canvas1.height = this.canvasHeight1
const ctx = canvas.getContext('2d')
// 加载图片
const image = await this.loadImage(this.imageUrl)
ctx.drawImage(image, 0, 0, this.canvasWidth, this.canvasHeight)
// 生成二维码
const qrCode = await QRCode.toCanvas(canvas1, this.qrCodeText, {
errorCorrectionLevel: 'H',
margin: 2,
width: this.canvasWidth1 / 1.5,
height: this.canvasHeight1 / 1.5
})
// 将二维码合成到图片上
const qrCodeX = (this.canvasWidth - qrCode.width) /28
const qrCodeY = (this.canvasHeight - qrCode.height) / 1.1
ctx.drawImage(qrCode, qrCodeX, qrCodeY)
// 绘画二维码边框
ctx.strokeStyle = 'rgba(148, 163, 184, 0.3)'
ctx.lineWidth = 15
ctx.strokeRect(
qrCodeX,
qrCodeY,
this.canvasWidth1 / 1.5,
this.canvasHeight1 / 1.5
)
// 绘画名称
ctx.font = 'bold 48px serif'
ctx.fillStyle = '' // 默认黑色
ctx.fillText(`${this.iKunName}`, 180, 50)
// 图片清晰化 - (devicePixelRatio)当前显示设备的物理像素分辨率与CSS 像素分辨率之比
// const img1 = document.createElement('img')
// img1.style.width
// img1.style.height
// 将画布转换为图片
const imageData = canvas.toDataURL('image/png')
this.imageData = imageData
// 下载合成后的图片至本地
const a = document.createElement('a')
const event = new MouseEvent('click')
a.download = `${this.iKunName}`
a.href = this.imageData
a.dispatchEvent(event)
},
loadImage(url) {
return new Promise((resolve, reject) => {
const image = new Image()
image.onload = () => resolve(image)
image.onerror = reject
image.src = url
})
}
},
}
</script>