在pc端生成如图所示二维码海报,且支持复制,下载二维码功能 安装好QRCode 和 html2canvas后
> <div style="padding: 20px">
<!-- 海报html元素 -->
<div
id="posterHtml"
class="posterBox"
:style="{backgroundImage: 'url(' + bgImgURL + ')' }"
>
<div class="posterContent">
{{ contentData }}
</div>
<!-- 二维码 -->
<div class="qrcodeBox">
<div id="qrcodeImg"></div>
</div>
</div>
<div>
<button
class="myButton"
@click="createPoster"
>生成海报</button>
<button
class="myButton"
@click="downloadPoster(posterImgURL,'海报名称')"
>下载海报</button>
</div>
<!--微信里,可长按保存或转发-->
<!-- <img
v-if="posterImgURL"
class="posterBox"
:src="posterImgURL"
> -->
</div>
</template>
<script>
import bgImgURL from '@/assets/images/common/codeBg.png'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
export default {
data() {
return {
bgImgURL: bgImgURL,
contentData: '我是一张分享海报', // 文案内容
posterImgURL: '' // 最终生成的海报图片URL
}
},
mounted() {
this.$nextTick(
() => {
this.createQrcode('https://www.baidu.com/')
}
)
},
methods: {
// 生成二维码
createQrcode(text) {
const qrcodeImgEl = document.getElementById('qrcodeImg')
qrcodeImgEl.innerHTML = ''
const qrcode = new QRCode(qrcodeImgEl, {
width: 100,
height: 100,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
})
qrcode.makeCode(text)
},
// 生成海报
createPoster() {
const that = this
const posterDOM = document.getElementById('posterHtml')
html2canvas(posterDOM, {
width: posterDOM.offsetWidth,
height: posterDOM.offsetHeight,
// 按比例增加分辨率
scale: window.devicePixelRatio, // 设备像素比
useCORS: true, // (图片跨域相关)
allowTaint: true, // 允许跨域(图片跨域相关)
logging: false,
letterRendering: true
}).then(function (canvas) {
that.posterImgURL = canvas.toDataURL('image/png')
that.copyImg()
})
},
copyImg() {
const parsedBase64 = this.parseBase64(this.posterImgURL)
const type = parsedBase64.type
// 将base64转为Blob类型
const bytes = atob(parsedBase64.data)
const ab = new ArrayBuffer(bytes.length)
const ua = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
ua[i] = bytes.charCodeAt(i)
}
const blob = new Blob([ab], { type })
navigator.clipboard.write([new ClipboardItem({ [type]: blob })])
this.$message.success('复制成功')
},
parseBase64(base64) {
const re = new RegExp('data:(?<type>.*?);base64,(?<data>.*)')
const res = re.exec(base64)
if (res) {
return {
type: res.groups.type,
ext: res.groups.type.split('/').slice(-1)[0],
data: res.groups.data
}
}
},
// 下载海报
downloadPoster(url, fileName) {
const a = document.createElement('a')
a.download = fileName
a.href = url
a.dispatchEvent(new MouseEvent('click'))
}
}
}
</script>
<style scoped>
/*海报*/
.posterBox {
position: relative;
width: 800px;
height: 300px;
background-repeat: no-repeat;
background-size: cover;
}
/*海报文案*/
.posterContent {
text-align: center;
color: white;
padding: 10px;
}
/*二维码*/
.qrcodeBox {
position: absolute;
bottom: 10px;
right: 10px;
}
/*按钮*/
.myButton {
background: none;
cursor: pointer;
padding: 5px 10px;
border-radius: 4px;
margin: 10px;
}
</style>