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) },
原文:https://www.cnblogs.com/aotuboke/p/14523789.html