html代碼
<view style="padding-top: 100rpx;"> <!-- <view class="tips"> <image src="../static/fingerprint.png" mode=""></image> <text></text> </view> --> <view class="posterImgBox"> <view id="poster"> <img class="image" :src="imageUrl" mode=""></img> <uqrcode v-if="!posterImgType" class="qrCodeImg" ref="uQRCode" :text="'https://www.wm319.com?page=/pages/wcatLoin/wcatLoin@userId=' + userData.id" :size="42" /> </view> </view> <view class="btns"> <view class="shareBtn" @click="renderScript.emitData"> <text>保存到相冊</text> </view> <view class="shareBtn" @click="shareBtn"> <image src="../static/weixin.png" mode=""></image> <text>分享到微信</text> </view> </view> </view>
注: uqrcode插件在uni-app插件市場導入項目即可直接用標簽方式使用
JS代碼(邏輯層)// 保存圖片到本地 downLoadImage(){ let base64 = this.imageUrl; const bitmap = new plus.nativeObj.Bitmap("test"); bitmap.loadBase64Data(base64, function() { const url = "_doc/" + new Date().getTime() + ".png"; // url為時間戳命名方式 console.log('saveHeadImgFile', url) bitmap.save(url, { overwrite: true, // 是否覆蓋 quality: 10 // 圖片清晰度 }, (i) => { uni.saveImageToPhotosAlbum({ filePath: url, success: function() { uni.showToast({ title: '圖片保存成功', icon: 'none' }) bitmap.clear() } }); }, (e) => { uni.showToast({ title: '圖片保存失敗', icon: 'none' }) bitmap.clear() }); }, (e) => { uni.showToast({ title: '圖片保存失敗', icon: 'none' }) bitmap.clear() }); }, // 點擊分享到微信 shareReachWeiXin(){ uni.share({ provider: "weixin", scene: "WXSceneSession", type: 0, href: "", // 跳轉的地址 title: "XXXX", // 分享的標題 summary: "邀請你和我一起成長", imageUrl: "logo.png", success: function (res) { console.log("success:" + JSON.stringify(res)); }, fail: function (err) { console.log("fail:" + JSON.stringify(err)); } }); },
// 接收生成的圖片
receiveRenderData(val){
this.imageUrl = val;
this.posterImgType = true;
this.downLoadImage();
},
注:額外創建script建立renderjs
<script module="renderScript" lang="renderjs"> import html2canvas from '../../utils/html2canvas.min.js'; export default { data() { return { } }, mounted() {}, methods: { // 發送數據到邏輯層 emitData(e, ownerVm) { const dom = document.getElementById('poster') html2canvas(dom, { width: dom.clientWidth, //dom 原始寬度 height: dom.clientHeight, scrollY: 0, // html2canvas默認繪制視圖內的頁面,需要把scrollY,scrollX設置為0 scrollX: 0, foreignObjectRendering: true, // 是否在瀏覽器支持的情況下使用ForeignObject渲染 useCORS: true, // 是否嘗試使用CORS從服務器加載圖像 async: false, // 是否異步解析和呈現元素 background: "#ffffff", dpi: 300 }).then((canvas) => { // console.log(e, ownerVm); // console.log(canvas) // 將生產的canvas轉為base64圖片3 ownerVm.callMethod('receiveRenderData', canvas.toDataURL('image/png')) }); } } }; </script>
