生成动态海报,带二维码
前提:装插件html2canvas 、QRCode
<div class="dialog-content" id="posterHtml"> <img :src="posterPageTemplate"> <!-- 二维码 --> <div class="qrcode"><div id="qrcodeImg"></div></div> <p class="txt-center tips fs-24">长按图片识别二维码,立即申请!</p> </div>
<script> import html2canvas from 'html2canvas' import QRCode from 'qrcodejs2' import utils from '@/components/utils' export default { props: { visible: { type: Boolean, default: false } }, data () { return { isShow: false, config: { // 二维码参数 downloadFilename: '专属海报' }, posterImg: '', // 最终生成的海报图片 qrcode: '', qrcodeUrl: '', // 二维码链接 posterPageTemplate: '' // 专属海报页背景图 } }, mounted () { this.getData() }, methods: { imageUrlToBase64 (url) { // 一定要设置为let,不然图片不显示 let image = new Image() // 解决跨域问题 image.setAttribute('crossOrigin', 'anonymous') let imageUrl = url image.src = imageUrl // image.onload为异步加载 image.onload = () => { let canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height let context = canvas.getContext('2d') context.drawImage(image, 0, 0, image.width, image.height) let quality = 0.8 // 这里的dataurl就是base64类型 let dataURL = canvas.toDataURL('image/jpeg', quality)// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长! this.posterPageTemplate = dataURL if (utils.isIOS && ('addEventListener' in document)) { this.$loading.show() console.log('ios设备') setTimeout(() => { this.showPoster() }, 1000) } else { console.log('android设备') this.showPoster() } } }, // 关闭弹框 closeDialog () { this.$emit('close') // 清除二维码 this.qrcode.clear() }, getData () { // posterImg 请求接口获取海报图片 // 请求接口开始 ====== let posterImg = '' this.imageUrlToBase64(posterImg) }, createQrcode () { // 生成二维码 const qrcodeImgEl = document.getElementById('qrcodeImg') qrcodeImgEl.innerHTML = '' this.qrcode = new QRCode(qrcodeImgEl, { width: 105, height: 105, colorDark: '#000000', colorLight: '#ffffff', text: this.qrcodeUrl, // 设置二维码内容或跳转地址 correctLevel: QRCode.CorrectLevel.H }) }, createPoster () { this.createQrcode() // 生成海报 const _this = this const domObj = document.getElementById('posterHtml') html2canvas(domObj, { useCORS: true, // 允许图片跨域 allowTaint: false, logging: false, letterRendering: false, scale: window.devicePixelRatio }).then((canvas) => { // 在微信里,可长按保存或转发 _this.posterImg = canvas.toDataURL() // console.log(_this.posterImg) }) }, // 显示海报 showPoster () { this.$nextTick(() => { this.createPoster() this.createQrcode() }) this.$loading.hide() this.isShow = true } } } </script>