微信小程序中生成二维码工具:weapp.qrcode.js

前言

在近期的小程序开发中,有一个离线生成二维码的需求。当时想到了一些优秀的前端开源库 jquery-qrcodenode-qrcode,因为小程序中没有DOM的概念,这些库在小程序中并不适用。html

因此,针对微信小程序的特色,封装了 weapp.qrcode.js ,用于在小程序中快速生成二维码。效果以下图:前端

下面来介绍一下使用方法:node

使用

建立canvas标签

先在 wxml 文件中,建立绘制的 canvas,并定义好 width, height, canvasId 。因为小程序没有动态建立标签的api,因此这一步不能省略。jquery

<canvas style="width: 200px; height: 200px;" canvas-id="myQrcode"></canvas>
复制代码

调用绘制方法

因为微信小程序不支持引入NPM包,能够将dist目录下,weapp.qrcode.min.js 拷贝至项目中。git

若是你的小程序使用了支持引入NPM包的框架,如 wepy , 也能够直接安装 weapp-qrcode NPM包。github

npm install weapp-qrcode --save
复制代码

引入 js 文件后,调用 drawQrcode() 绘制二维码。shell

import drawQrcode from 'weapp-qrcode'
// 或者,将 dist 目录下,weapp.qrcode.min.js 复制到项目目录中
// import drawQrcode from '../../utils/weapp.qrcode.min.js'

drawQrcode({
  width: 200,
  height: 200,
  canvasId: 'myQrcode',
  text: 'https://github.com/yingye'
}
复制代码

API说明

参数 说明 示例
width 必须,二维码宽度,与canvaswidth保持一致 200
height 必须,二维码高度,与canvasheight保持一致 200
canvasId 必须,绘制的canvasId 'myQrcode'
text 必须,二维码内容 'https://github.com/yingye'
typeNumber 非必须,二维码的计算模式,默认值-1 8
correctLevel 非必须,二维码纠错级别,默认值为高级,取值:{ L: 1, M: 0, Q: 3, H: 2 } 1
background 非必须,二维码背景颜色,默认值白色 '#ffffff'
foreground 非必须,二维码前景色,默认值黑色 '#000000'

若是想更深刻的了解二维码的原理,推荐你们阅读 二维码的生成细节和原理npm

原始文档

https://github.com/yingye/weapp-qrcode ,若是以为还不错,记得给个star奥~canvas

相关文章
相关标签/搜索