微信小程序字符串转为二维码(JavaScript)

最近在开发微信小程序时,遇到一个需要将服务端接口返回的base64格式的字符串转为二维码展示,在参考了一些大佬的思路后,最终顺利完成此功能。以下是我的思路及示例代码。

  1. 项目结构
    项目结构
    我习惯在项目的工具类目录下创建单独的文件夹以区分其他的工具,不这样分也可以,只是后面import的时候相对路径需要根据自己实际的修改。
  2. 工具类
    encryption.js,JSEncrypt.js,qrcode.js我已上传网盘,在文末有链接和提取码,自行获取。
  3. 生成二维码
    最重要的部分是qrcodeAction.js,这是生成二维码的关键,所需的二维码参数都在这里转换或定义。代码如下:
import { base64DecToArr, uint8ArrayToString } from './encryption';

function getQrcodeParams(config) {
	if (config && config.qrcode) {
		let qrArr = base64DecToArr(config.qrcode);
		let strInUtf = uint8ArrayToString(qrArr);
		const baseWidth = config.width;
		const baseHeight = config.height;
		const canvasId = config.id;
		const newAllWidth = wx.getSystemInfoSync().windowWidth;
		const codeWidth = (newAllWidth * baseWidth) / 750;
		const codeHeight = (newAllWidth * baseHeight) / 750;
		return {
			text: strInUtf,
			width: codeWidth,
			height: codeHeight,
			correctLevel: config.correctLevel || 0,
			image: {
				imageResource: '/image/logo.png',
				width: 80, // 建议不要设置过大,以免影响扫码
				height: 80, // 建议不要设置过大,以免影响扫码
				round: false // Logo图片是否为圆形
			},
			canvasId: canvasId
		};
	} else {
		return null;
	}
}

module.exports = {
  getQrcodeParams: getQrcodeParams
}
  1. 实际使用
    以下是我在实际页面使用的例子,供参考。
    a.在data定义codeInfo对象
codeInfo: {
  width: 470,
  height: 470,
  qrcode: '',
  correntLevel: 0,
  foreground: '#000000'
}

b.引入QrcodeAction和QRcode方法

import QrcodeAction from '../../utils/qr_code/qrcodeAction.js';
import { QRcode } from '../../utils/qr_code/qrcode.js'

c.在页面引入画布组件

<canvas style="width: {{codeInfo.width}}rpx; height: {{codeInfo.height}}rpx;" canvas-id="codewrap"></canvas>

d.生成二维码

let codeInfo = that.data.codeInfo
codeInfo.qrcode = data.data.codeContent
codeInfo = Object.assign(codeInfo, {id: 'codewrap'})
let params = QrcodeAction.getQrcodeParams(codeInfo)
if (params && params.text) {
  QRcode(params)
}

以上是我在我自己项目中使用的过程,供参考,实际使用还需要大家灵活变通。

附:encryption.js,JSEncrypt.js,qrcode.js资源
链接:https://pan.baidu.com/s/1r8HPxgMoo_ZpHA6284Ckmw
提取码:e3zs

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值