uni-app html2canvas在web端兼容性挺好的,但是對於app來說就不太行
uni-app App是vue頁面,無法獲取window對象,所以我們就需要配合render.js來完成canvas的繪制
人為觸發比如點擊按鈕實現起來很方便,但是有時候我們需要進來就執行繪制的方法,那么就需要如下操作:
在開發過程中我們將HTML2canvas封裝成一個組件,通過prop傳遞ID參數
在組件中,通過prop接收ID的,ID的變化來觸發render.js里面的函數
html2canvas.vue:
<template> <view> <view class="html2canvas" :prop="domId" :change:prop="html2canvas.create"> <slot></slot> </view> </view> </template> <script> import { base64ToPath } from '@/utils/image-tools.js'; export default { name: 'html2canvas', props: { domId: { type: String, required: true } }, methods: { async renderFinish(base64) { try{ const imgPath = await base64ToPath(base64, '.jpeg'); console.log(imgPath) this.$emit('renderFinish', imgPath); }catch(e){ //TODO handle the exception console.log('html2canvas error', e) } }, showLoading() { uni.showLoading() }, hideLoading() { uni.hideLoading(); } } } </script> <script module="html2canvas" lang="renderjs"> import html2canvas from 'html2canvas'; export default { methods: { async create(domId) { try { const timeout = setTimeout(async ()=> { const shareContent = document.querySelector(domId); const canvas = await html2canvas(shareContent,{ width: shareContent.offsetWidth,//設置canvas尺寸與所截圖尺寸相同,防止白邊 height: shareContent.offsetHeight,//防止白邊 logging: true, useCORS: true }); const base64 = canvas.toDataURL('image/jpeg', 1); this.$ownerInstance.callMethod('renderFinish', base64); clearTimeout(timeout); }, 500); } catch(error){ console.log(error) } } } } </script> <style lang="scss"> </style>
index.vue:
index頁面直接獲取生成后的數據
<html2canvas ref="html2canvas" :domId="domId" @renderFinish="renderFinish"> <view class="invite-image" id="poster" :class="i18n.locale=='en'?'en':'zh'"> <view class="code-image"> <view class="qrimg"> <tki-qrcode ref="qrcode" :cid="cid" :val="dowaload" :size="size" :unit="unit" :onval="onval" foreground="#000000" pdground="#000000" :loadMake="loadMake" :loadingText="i18n.t('base.textLoading')" @result="qrR" /> </view> </view> <view class="invite-text">{{i18n.t('user.invite.inviteCode')}}</view> <view class="invite-code">{{userInfo.code}}</view> </view> </html2canvas>
中間是二維碼部分可以忽略,從而就可以實現海報的繪制,保存的時候重復的照片只會保存一張,有時候可能會失敗,就要返回重新進入再次保存
IOS可能存在錯誤,由於時間有限,沒來得及研究,就只看了安卓的,后面有機會再研究,要是誰做出來了,也歡迎分享!
/** * 渲染完畢接收圖片 * @param {String} filePath */ renderFinish(filePath) { console.log(filePath); this.filePath = filePath; that.btnShow=true console.log("filePath", filePath) },