0
点赞
收藏
分享

微信扫一扫

Uniapp 微信小程序前端生成海报并保存 解决方案

哈哈我是你爹呀 2022-04-27 阅读 260

前端时间自己做了个小程序,然后要让用户能够分享页面去外部生态。

所以第一时间就想到了生成二维码海报的形式去做。

先看一下最终效果。

 保存下来的图片是这样子的。

实现生成这一个功能,需要有以下步骤。

  1. 生成微信小程序二维码,并临时保存到本地

  2. 绘制Canvas画布内容(标题、描述、SLOGEN,二维码,提示语)

  3. Canvas画布转临时地址

  4. 保存图片功能

下面开始为实际的开发,先申明因为本次是用Uniapp的Canvas、getFileSystemManager等一些API,所以代码仅适用于Uniapp。

其实思路也是一样的,用在微信原生小程序的话也只是某些API有变动而已,大同小异。

1. 生成微信小程序二维码,并临时保存到本地

官方文档API wxacode.getUnlimited | 微信开放文档

官方是有三个生成二维码的接口的,各有不同,大家可以自行了解一下,本文采用的是 getUnlimited 方式。(通过该接口生成的小程序码,永久有效,数量暂无限制,但是携带的参数最大32个可见字符 )

保存临时地址也是用了微信的FileSystemManager.writeFileSync API 

可以让Base64上传到本地,转换成一个地址,从而让canvas可以绘制出来。

官方文档API FileSystemManager.writeFileSync(string filePath, string|ArrayBuffer data, string encoding) | 微信开放文档

const bufferToBase64 = (arraybuffer) => {
	return `data:image/jpeg;base64,${uni.arrayBufferToBase64(arraybuffer)}`;
}

const bufferToJson = (arraybuffer) => {
    try {
		const uint8Arr = new Uint8Array(arraybuffer);
		const encodedString = String.fromCharCode.apply(null, uint8Arr);
		const decodedString = decodeURIComponent(escape(encodedString))
			
		return JSON.parse(decodedString)
	} catch(e) {
		return {}
	}
}

/**
 * 生成微信小程序二维码
 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
 * @description 请勿用于生产,生成微信小程序二维码应该是由 后端/云函数 去生成,因为前端不允许直接调用api.weixin.qq.com
 * @param {string} scene 页面参数
 * @param {string} page 页面路径
 * @param {string} env_version 打开的小程序版本
 * @param {...} 更多参数请自行根据文档扩展
 * @return {string} 二维码临时路径
*/
async createWxQrcode({scene, page, env_version}) {
	return await uni.request({
		url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${this.wxAccessToken}`,
	    method: 'POST',
		data: {
		    scene,
			page,
			env_version
		},
		responseType: "arraybuffer", // 返回是arraybuffer格式
	})
		.then((data) => {
			const [err, res] = data;
						
			if (err) {
				console.log(err)
				uni.hideLoading()
				throw new Error('生成微信小程序二维码错误')
			}
						
			const jsonRes = bufferToJson(res.data)
			if (!jsonRes.errcode) {
				return bufferToBase64(res.data)
			} else {
				return null
			}
		})
}

// 生成微信小程序二维码,并临时保存到本地
const wxQrcode = await this.createWxQrcode(this.createQrcodeInfo)
// 由于小程序canvas无法绘制base64图片,所以先保存到本地,绘制完再删除
const filePath = `${wx.env.USER_DATA_PATH}/tmp-share-qrcode-${Date.now()}`
const imageData = wxQrcode.replace(/^data:image\/\w+;base64,/, "");
const fs = uni.getFileSystemManager()
fs.writeFileSync(filePath, imageData, 'base64')

console.log(filePath) // 此值为微信小程序二维码临时地址

2. 绘制Canvas画布内容(标题、描述、SLOGEN,二维码,提示语)

这部分就是Canvas的绘制,主要就是对CanvasAPI的一些调用。

具体的API可以看此文档,uni-app CanvasAPI文档

const ctx = uni.createCanvasContext('qrCodeCanvas')
const canvasInfo = {
	canvasWidth: 650,
	canvasHeight: 700,
	title: '都城大饭店',
	desc: '😋目标是吃上都城大饭店最贵的菜',
	qrCode: '',
	tips: '长按或扫描二维码,立刻加入群聊'
}
const upx2px = uni.upx2px

// 设置背景色
ctx.setFillStyle('#fff')
ctx.fillRect(0, 0, upx2px(canvasInfo.canvasWidth), upx2px(canvasInfo.canvasHeight))

// 绘制群信息模块
// 群标题
ctx.font = `bold ${upx2px(54)}px arial`
ctx.setFillStyle('#000')
canvasWraptitleText(ctx, canvasInfo.title, upx2px(40), upx2px(100), upx2px(canvasInfo.canvasWidth) - upx2px(70), upx2px(60), 1)
// 群描述
ctx.font = `${upx2px(42)}px arial`
ctx.setFillStyle('#999')
canvasWraptitleText(ctx, canvasInfo.desc, upx2px(40), upx2px(190), upx2px(canvasInfo.canvasWidth) - upx2px(70), upx2px(60), 2)
// Logo
ctx.font = `bold ${upx2px(46)}px arial`
ctx.setFillStyle('#000')
ctx.fillText('群搜搜', upx2px(canvasInfo.canvasWidth - 180), upx2px(canvasInfo.canvasHeight - 325))
ctx.font = `${upx2px(28)}px arial`
ctx.setFillStyle('#999')
ctx.fillText('海量微信群,免费加入,发布!', upx2px(canvasInfo.canvasWidth - 410), upx2px(canvasInfo.canvasHeight - 270))

// 绘制底部二维码模块
const footerWidth = upx2px(canvasInfo.canvasWidth)
const footerHeight = upx2px(canvasInfo.canvasHeight - 220)

// 绘制虚线
ctx.setLineDash([7, 10], 0)
ctx.beginPath()
ctx.moveTo(0, footerHeight)
ctx.lineTo(footerWidth, footerHeight)
ctx.setStrokeStyle('#d8d8d8')
ctx.stroke()

// 绘制二维码图片
const qrCodeSize = upx2px(150)
const qrCodeTop = footerHeight + upx2px(40)
const qrCodeLeft = upx2px(35)
ctx.drawImage(canvasInfo.qrCode, qrCodeLeft, qrCodeTop, qrCodeSize, qrCodeSize)
// 绘制二维码提示
const tipsWidth = qrCodeLeft + qrCodeSize + upx2px(18)
ctx.font = `${upx2px(26)}px arial`
ctx.setFillStyle('#666')
ctx.fillText(canvasInfo.tips, tipsWidth, qrCodeTop + qrCodeSize / 2 + 4)
ctx.draw()

3. Canvas画布转临时地址

只是绘制成Canvas的话,用户是无法保存的。

所以要把Canvas转成图片的形式,然后用户就可以长按保存或者直接按钮触发下载了。

这里是用到了 canvasToTempFilePath 的一个方法,具体文档可以看下面uni.canvasToTempFilePath(object, component) | uni-app官网

uni.canvasToTempFilePath({
  canvasId: 'qrCodeCanvas',
  quality: 1,
  fileType: 'jpg',
  success: (res) => {
    console.log(res.tempFilePath) // 生成图片的链接
    
    // 删除临时保存的文件
    fs.unlinkSync(filePath)
  }
})

4. 保存图片功能

既然海报已经从Canvas生成图片了,用户就可以下载了,为了方便用户,也就用 saveImageToPhotosAlbum API 来保存下载图片。

具体文档可以看 uni.chooseImage(OBJECT) | uni-app官网

最后

功能已经全部完成了,相关的代码已经托管再Github啦,欢迎运行指导。

举报

相关推荐

0 条评论