install
npm install --save html2canvas
在所需页面引入
import html2canvas from "html2canvas"
use
<div ref="codeRef" class="code text-white text-center p-20px relative mb-30px" > <p class="text-xl mb-10px"> {{ univName }} </p> <p>报名点</p> <img class="mt-22px" width="154" height="154" src="~assets/images/pages/opcenter/admissions/code.png" alt="报名二维码" /> <p class="absolute bottom-12 left-0 w-full text-xs"> 招生老师:{{ teacherName }} {{ formState.phone }} </p> </div> <a-button class="default-acctive mr-12px flex-shrink-0 block m-auto" @click="downloadCode" > 下载报名海报 </a-button>
vue中用ref来指定你需要转成图片下载的dom
const downloadCode = () => { html2canvas(this.$refs.codeRef).then(canvas => { const base64 = canvas.toDataURL(‘image/png‘) const myBlob = dataURLtoBlob(base64) const myUrl = URL.createObjectURL(myBlob) downloadFile(myUrl, ‘报名二维码‘) }) } const dataURLtoBlob = (dataurl: string) => { const arr: any[] = dataurl.split(‘,‘) const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) } const downloadFile = (url: string, name: string) => { const a = document.createElement(‘a‘) a.setAttribute(‘href‘, url) a.setAttribute(‘download‘, name) a.setAttribute(‘target‘, ‘_blank‘) const clickEvent = document.createEvent(‘MouseEvents‘) clickEvent.initEvent(‘click‘, true, true) a.dispatchEvent(clickEvent) }
参考链接:https://www.cnblogs.com/zouwangblog/p/11140568.html
参考链接:https://www.cnblogs.com/myflowers/p/13753540.html