在uniapp中實現微信小程序保存海報到手機相冊,主要涉及Canvas繪制和圖片保存。以下是關鍵步驟和代碼示例:
一、關鍵代碼展示:
1. 模板配置:頁面展示該海報,可直接查看,也可下載保存到手機相冊,html關鍵代碼如下:
<view class="content"><canvas class="canvas-poster" canvas-id="canvasposter"></canvas>
</view>
2. 海報繪制:js關鍵代碼如下:
//繪制到canvas
downloadQrcode: function() {var ctx = uni.createCanvasContext("canvasposter")let that = this// #ifdef MP-WEIXINuni.downloadFile({url: 'https://xxx.zexun.tech/getfile/statics/cdn/images/large_invite_bg.png', // 網絡圖片鏈接success: downloadResult => {if (downloadResult.statusCode === 200) {/* 繪制第一張照片*/// 參數說明:('圖片路徑',canvas的橫坐標,canvas的縱坐標,圖片的寬度,圖片的寬度)ctx.drawImage(downloadResult.tempFilePath, 0, 0, 750, 1624)// 繪制第二張圖片-base64-轉換真機可讀wx.getFileSystemManager().writeFile({filePath: wx.env.USER_DATA_PATH + "/test.png",data: that.codeBase64,encoding: 'base64',success: (res) => {ctx.drawImage(wx.env.USER_DATA_PATH + "/test.png", 164,816, 420, 420)ctx.setTextAlign("center")ctx.setFontSize(34) // 第一行文字ctx.fillStyle = '#2B5370'; // 設置文字顏色為白色ctx.fillText('我的邀請碼:'+ that.$userInfo.agentNo, 375,668) //文字內容、x坐標,y坐標ctx.setFontSize(26) // 第二行文字ctx.fillStyle = '#636D86'; // 設置文字顏色為白色ctx.fillText('掃一掃下方二維碼,成為我的業務伙伴', 365,782) //文字內容、x坐標,y坐標uni.showLoading({title: "圖片生成中...",})ctx.draw(false,setTimeout(() => {that.getTempFilePath()}, 2500))}})}},fail: () => {uni.showToast({title: '下載失敗',icon: 'none'});}});// #endif
},
//獲取臨時路徑
getTempFilePath: function() {// 當前畫布指定區域的內容導出生成指定大小的圖片,并返回文件路徑uni.canvasToTempFilePath({canvasId: "canvasposter",success: (res) => {console.log(res.tempFilePath)this.saveImageToPhotosAlbum(res.tempFilePath) //保存到相冊},})
},
//把生成的圖片保存至相冊
saveImageToPhotosAlbum: function(imgUrl) {uni.hideLoading()if (imgUrl) {uni.saveImageToPhotosAlbum({filePath: imgUrl,success: (res) => {uni.showToast({title: "保存成功",icon: "success",duration: 2000,})},fail: (err) => {uni.showToast({title: "保存失敗",icon: "none",duration: 2000,})},})} else {uni.showToast({title: "繪制中……",icon: "loading",duration: 3000,})}
},
3. 樣式css關鍵代碼如下:
/* 繪制圖片canvas樣式 */
.canvas-poster {position: fixed;width: 750px;height: 1624px;top: 100%;left: 100%;
}
二、完整代碼附錄:
<template><view class="content"><!-- #ifdef MP-WEIXIN --><view class="guide_header_page2"><view :style="{ height: statusBarHeight }"></view><view class="guide_title" :style="{ height: navigationBarHeight, lineHeight:navigationBarHeight }"><uni-icons type="back" size="22" color="#232323" @click="goBack" class="icon"></uni-icons><text>我的邀請碼</text></view></view><!-- #endif --><view class="invite"><image src="https://xxx.zexun.tech/getfile/statics/cdn/images/large_invite_bg.png" mode="widthFix"class="bg" /><view class="invite_title">我的邀請碼:{{$userInfo.agentNo}}</view><view class="invite_tip">掃一掃下方二維碼,成為我的業務伙伴</view><image :src="'data:image/png;base64,' + codeBase64" mode="widthFix" class="qrcode" /><view class="invite_btn"><u-button text="保存圖片" shape="circle" color="linear-gradient(to right, #26B6B9, #21CE98)" @click="downloadQrcode"></u-button></view></view><canvas class="canvas-poster" canvas-id="canvasposter"></canvas></view>
</template><script>import {getInvitationCode} from '@/common/api.js'export default {data() {return {// #ifdef MP-WEIXINstatusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px', // 狀態欄高度capBarHeight: uni.getMenuButtonBoundingClientRect().height + 'px', // 膠囊高度navigationBarHeight: (uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight) * 2 + uni.getMenuButtonBoundingClientRect().height + 'px', // 導航欄高度barCapHeight: (uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight) * 2 + uni.getMenuButtonBoundingClientRect().height + uni.getSystemInfoSync().statusBarHeight + 'px', //導航欄高度+狀態欄高度// #endifcodeBase64: null,type: '2', // 2-服務商邀請碼,3-業務員邀請碼}},onLoad() {this.getInvitationCode()},methods: {goBack() {uni.navigateBack()},// 獲取二維碼getInvitationCode() {uni.showLoading({mask: true})getInvitationCode({inviteCode: this.$store.state.$userInfo.agentId,type: this.type}).then((res) => {uni.hideLoading()this.codeBase64 = res.data}).catch((err) => {uni.hideLoading()console.log(err)})},//繪制到canvasdownloadQrcode: function() {var ctx = uni.createCanvasContext("canvasposter")let that = this// #ifdef MP-WEIXINuni.downloadFile({url: 'https://xxx.zexun.tech/getfile/statics/cdn/images/large_invite_bg.png', // 網絡圖片鏈接success: downloadResult => {if (downloadResult.statusCode === 200) {/* 繪制第一張照片*/// 參數說明:('圖片路徑',canvas的橫坐標,canvas的縱坐標,圖片的寬度,圖片的寬度)ctx.drawImage(downloadResult.tempFilePath, 0, 0, 750, 1624)// 繪制第二張圖片-base64-轉換真機可讀wx.getFileSystemManager().writeFile({filePath: wx.env.USER_DATA_PATH + "/test.png",data: that.codeBase64,encoding: 'base64',success: (res) => {ctx.drawImage(wx.env.USER_DATA_PATH + "/test.png", 164,816, 420, 420)ctx.setTextAlign("center")ctx.setFontSize(34) // 第一行文字ctx.fillStyle = '#2B5370'; // 設置文字顏色為白色ctx.fillText('我的邀請碼:'+ that.$userInfo.agentNo, 375,668) //文字內容、x坐標,y坐標ctx.setFontSize(26) // 第二行文字ctx.fillStyle = '#636D86'; // 設置文字顏色為白色ctx.fillText('掃一掃下方二維碼,成為我的業務伙伴', 365,782) //文字內容、x坐標,y坐標uni.showLoading({title: "圖片生成中...",})ctx.draw(false,setTimeout(() => {that.getTempFilePath()}, 2500))}})}},fail: () => {uni.showToast({title: '下載失敗',icon: 'none'});}});// #endif// #ifndef MP-WEIXIN/* 繪制第一張照片*/// 參數說明:('圖片路徑',canvas的橫坐標,canvas的縱坐標,圖片的寬度,圖片的寬度)ctx.drawImage("https://jsfzapi.zexun.tech/getfile/statics/cdn/images/invite_bg.png", 0, 0,750, 1624)/* 繪制第二張照片*/ctx.drawImage("data:image/png;base64," + this.codeBase64, 164, 912, 420, 420)ctx.setTextAlign("center")ctx.setFontSize(32)ctx.setTextAlign("center")ctx.fillText(this.$realAgentInfo.shortName, 375, 880) //文字內容、x坐標,y坐標uni.showLoading({title: "圖片生成中...",})ctx.draw(false,setTimeout(() => {this.getTempFilePath()}, 1500))// #endif},//獲取臨時路徑getTempFilePath: function() {// 當前畫布指定區域的內容導出生成指定大小的圖片,并返回文件路徑uni.canvasToTempFilePath({canvasId: "canvasposter",success: (res) => {console.log(res.tempFilePath)this.saveImageToPhotosAlbum(res.tempFilePath) //保存到相冊},})},//把生成的圖片保存至相冊saveImageToPhotosAlbum: function(imgUrl) {uni.hideLoading()if (imgUrl) {uni.saveImageToPhotosAlbum({filePath: imgUrl,success: (res) => {uni.showToast({title: "保存成功",icon: "success",duration: 2000,})},fail: (err) => {uni.showToast({title: "保存失敗",icon: "none",duration: 2000,})},})} else {uni.showToast({title: "繪制中……",icon: "loading",duration: 3000,})}},},}
</script><style lang="scss" scoped>/* 繪制圖片canvas樣式 */.canvas-poster {position: fixed;width: 750px;height: 1624px;top: 100%;left: 100%;}.content {.invite {width: 100%;position: relative;.bg {width: 750rpx;}.invite_title {min-width: 418rpx;position: absolute;left: 52%;transform: translateX(-50%);top: 630rpx;font-weight: bold;font-size: 34rpx;color: #2B5370;}.invite_tip {min-width: 442rpx;position: absolute;left: 50%;transform: translateX(-50%);top: 766rpx;font-weight: 500;font-size: 26rpx;color: #636D86;}.qrcode {width: 420rpx;height: 420rpx;left: 50%;transform: translateX(-50%);top: 830rpx;position: absolute;}.invite_btn {width: 484rpx;height: 76rpx;bottom: 176rpx;position: absolute;z-index: 999;left: 50%;transform: translateX(-50%);}}}
</style>
三、效果圖展示:
提示:使用 uni.downloadFile 下載網絡圖片 https://xxx.xxx 等,需要在小程序后臺配置服務器域名;
有什么疑問,可以評論區回復,大家一起探討~