安装包
npm install --save qrcodejs2 npm install --save html2canvas
HTML
<div class="scan"> <div ref="imageDom" class="qrBox" v-if="isQRCode"> <img class="qrbj" src="../../assets/img/qrbg.png"> <div class="qrCon"> <div class="qrTitle">扫码关注</div> <div class="qrCanvas"> <div class="qrBorder"><div id="qrcode" style=" 150px;height:150px"></div></div> </div> </div> </div> <img v-else :src="imgUrl" class="qrImg"> </div>
JS
import QRCode from 'qrcodejs2' import html2canvas from 'html2canvas' export default { data () { return { isQRCode: true, imgUrl: '' } }, mounted () { this.qrcode('https://img0.baidu.com/it') }, methods: { /* 扫码签名 */ qrcode (text) { // 生成二维码 let qrcode = new QRCode('qrcode', { 150, height: 150 }) qrcode.makeCode(text) this.clickGeneratePicture() }, /** * 将页面指定节点内容转为图片 * 1.拿到想要转换为图片的内容节点DOM; * 2.转换,拿到转换后的canvas * 3.转换为图片 */ clickGeneratePicture () { // 生成图片
// let targetDom = document.getElementById('imageDom')
// let targetWidth = targetDom.offsetWidth
// let targetHeight = targetDom.offsetHeight
// let canvas = document.createElement('canvas')
// // let scale = window.devicePixelRatio
// var scale = 1 // 放大倍数
// canvas.width = targetWidth * scale
// canvas.height = targetHeight * scale
// canvas.style.width = targetWidth * scale + 'px'
// canvas.style.height = targetHeight * scale + 'px'
// canvas.getContext('2d').scale(scale, scale)
// html2canvas(targetDom, {
// allowTaint: false,
// scale,
// canvas,
// logging: false,
// useCORS: true, // 【重要】开启跨域配置
// targetWidth,
// height: targetHeight,
// ignoreElements: (element) => {
// if (element.id === 'printHide') {
// return true
// }
// }
// }).then(canvas => {
// this.isQRCode = false
// this.imgUrl = canvas.toDataURL('image/png', 1.0)
// })
html2canvas(this.$refs.imageDom).then(canvas => { // 转成图片,生成图片地址 this.isQRCode = false this.imgUrl = canvas.toDataURL('image/png') // 可将 canvas 转为 base64 格式 }) } } }
效果图