更新记录

4.0.6(2022-12-12) 下载此版本

修复getDrawModules,第一次获取结果正常,后续获取tile模块不存在的问题;
修复安卓type:normal因Canvas API使用了小数或为0的参数导致生成异常的问题(注:安卓非2d Canvas部分API参数不支持携带小数,部分API参数必须大于0)。

4.0.1(2022-11-28) 下载此版本

优化组件loading属性的表现;
新增组件type选项normal,以便于在某些条件编译初始为type=2d时还可以选择使用非2d组件类型;
修复组件条件编译在其他编辑器语法提示报错;
修复原生对es5的支持。

4.0.0(2022-11-21) 下载此版本

v4版本源代码全面开放,开源地址:https://github.com/Sansnn/uQRCode

升级说明:v4为大版本更新,虽然已尽可能兼容上一代版本,但不可避免的还是存在一些细节差异,若更新后出现问题,请参考对照v3 文档v4 文档进行修改。

查看更多

平台兼容性

Vue2 Vue3
App 快应用 微信小程序 支付宝小程序 百度小程序 字节小程序 QQ小程序
app-vue app-nvue
钉钉小程序 快手小程序 飞书小程序 京东小程序
× × × ×
H5-Safari Android Browser 微信浏览器(Android) QQ浏览器(Android) Chrome IE Edge Firefox PC-Safari

介绍

uQRCode是一款基于Javascript环境开发的二维码生成插件,适用所有Javascript运行环境的前端应用和Node.js应用。

uQRCode可扩展性高,它支持自定义渲染二维码,可通过uQRCode API得到二维码绘制关键信息后,使用canvassvgjs操作dom的方式绘制二维码图案。还可自定义二维码样式,如随机颜色、圆点、方块、块与块之间的间距等。

欢迎加入群聊【uQRCode交流群】:695070434

微信小程序搜索“柚子二维码”,或扫描下方小程序码体验。

uQRCode设计器

示例

uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器 uQRCode设计器

快速上手

uni-app中,我们更推荐使用组件方式来生成二维码,组件方式大大提高了页面的可读性以及避开了一些平台容易出问题的地方,当组件无法满足需求的时候,再考虑切换成原生方式。

官方文档:https://uqrcode.cn/doc

github地址:https://github.com/Sansnn/uQRCode

npm地址:https://www.npmjs.com/package/uqrcodejs

uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=1287

原生方式

原生方式仅需要获取uqrcode.js文件便可使用。详细配置请移步到:文档 > 原生

安装

  1. 通过npm安装,成功后即可使用importrequire进行引用。

    # npm安装
    npm install uqrcodejs
    # 或者
    npm install @uqrcode/js
  2. 通过项目开源地址获取uqrcode.js,下载uqrcode.js后,将其复制到您项目指定目录,在页面中引入uqrcode.js文件即可开始使用。

引入

  • 通过import引入。

    // npm安装
    import UQRCode from 'uqrcodejs'; // npm install uqrcodejs
    // 或者
    import UQRCode from '@uqrcode/js'; // npm install @uqrcode/js
  • Node.js通过require引入。

    // npm安装
    const UQRCode = require('uqrcodejs'); // npm install uqrcodejs
    // 或者
    const UQRCode = require('@uqrcode/js'); // npm install @uqrcode/js
  • 原生浏览器环境,在js脚本加载时添加到window

    <script type="text/javascript" src="uqrcode.js"></script>
    <script>
    var UQRCode = window.UQRCode;
    </script>

简单用法

uQRCode基于Canvas API封装了一套方法,建议开发者使用canvas生成,一键调用,非常方便。以下是示例:

  • HTML示例

    • DOM部分

      <canvas id="qrcode" width="200" height="200"></canvas>
    • JS部分

      // 获取uQRCode实例
      var qr = new UQRCode();
      // 设置二维码内容
      qr.data = "https://uqrcode.cn/doc";
      // 设置二维码大小,必须与canvas设置的宽高一致
      qr.size = 200;
      // 调用制作二维码方法
      qr.make();
      // 获取canvas元素
      var canvas = document.getElementById("qrcode");
      // 获取canvas上下文
      var canvasContext = canvas.getContext("2d");
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext;
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas();
  • uni-app示例

    • Template部分

      <canvas id="qrcode" canvas-id="qrcode" style="width: 200px;height: 200px;"></canvas>
    • JS部分

      onReady() {
      // 获取uQRCode实例
      var qr = new UQRCode();
      // 设置二维码内容
      qr.data = "https://uqrcode.cn/doc";
      // 设置二维码大小,必须与canvas设置的宽高一致
      qr.size = 200;
      // 调用制作二维码方法
      qr.make();
      // 获取canvas上下文
      var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件,this必须传入
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext;
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas();
      }
  • 微信小程序,推荐使用Canvas 2D,关于Canvas 2D的使用请参考微信开放文档。

高级用法

考虑到部分平台可能不支持canvas,所以uQRCode并没有强制要求和canvas一起使用,您还可以选择其他方式来生成二维码,例如使用js操作dom进行绘制或是使用svg绘制等。以下是示例:

  • uni-app v-for+view
<template>
  <view>
    <view class="qrcode">
      <view v-for="(row, rowI) in modules" :key="rowI" style="display: flex;flex-direction: row;">
        <view v-for="(col, colI) in row" :key="colI">
          <view v-if="col.isBlack" style="width: 10px;height: 10px;background-color: black;">
            <!-- 黑色码点 -->
          </view>
          <view v-else style="width: 10px;height: 10px;background-color: white;">
            <!-- 白色码点 -->
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import UQRCode from '../../uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';

  export default {
    data() {
      return {
        modules: []
      }
    },
    onLoad() {
      const qr = new UQRCode();
      qr.data = 'uQRCode';
      qr.make();
      this.modules = qr.modules;
    },
    methods: {

    }
  }
</script>
  • js操作dom
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>uQRCode二维码生成</title>
</head>
<body>
    <div id="qrcode" style="position: relative;"></div>
    <script type="text/javascript" src="uqrcode.js"></script>
    <script>
    // 引入uQRCode
    var UQRCode = window.UQRCode;
    // 获取uQRCode实例
    var qr = new UQRCode();
    // 设置二维码内容
    qr.data = "https://uqrcode.cn/doc";
    // 设置二维码大小,必须与canvas设置的宽高一致
    qr.size = 200;
    // 设置二维码前景图,可以是路径
    qr.foregroundImageSrc =
        'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAC3xJREFUeJztnd1vFNcZxodSJ3y3EL7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Gzdu6KRgIWCguCQFQ8K1qpKCqSOt9dyPICHi/uPHj+u0eQEgyALPkHLQmJs2Dx77ps2rlFiy89atW9d870CXsnLz5s1RpXUETiyphi2ZehWtxEq9unnz5mOPHj263+xKLpQyOTn5VWtrKzJp7zPKU6/KrNG+abzVsOWanLijo+OETk7sX+AREjkb7smJZevwDFfOsAVyiG9e6bs7OX33RZ2+2y5K+u5LnL6706hT+m61L1ET3Lca7gnukdRdJ7ivnOC+1QiZ4F6FIkOXhAK6aHKIg+joMWLAkPg1vgHMQrE0gCfjbdY7EZWsXyfX+QB78Kphr1W9xB5tZc/WKjDgqW/f4SxqBy+hoKkh/qGj38QvhriIySOeBADCOs3LfFN7I649XNfdXHd40MGebGWP4NVq9k6F4Ruq3IraUtDEEPfQGYE0wGAsjckjmuMWvgm0ngQrGXHJerZx3bewF8+zN2vYK3j2rBEwTLmVRUY5FNlaAAbzFFDHjB5PAMbV6/hG8FRsjIk2cJ3XsQer2ZOV7NESo9QqVBihgMiidvQSTItRgoOmiKdgBWsla1XEJesp672MvZAQWowSCBmiagKhlkUOqXAkIAkpjpL1l344IdQVhrM4X0SFpGpxxOWsr5cvTSleNxM36RK18n+GJEwNAYal3QAAAABJRU5ErkJggg==';
    // 调用制作二维码方法
    qr.make();

    var drawModules = qr.getDrawModules();
    // 遍历drawModules创建dom元素
    var qrHtml = '';
    for (var i = 0; i < drawModules.length; i++) {
        var drawModule = drawModules[i];
        switch (drawModule.type) {
        case 'tile':
            /* 绘制小块 */
            qrHtml += `<div style="position: absolute;left: ${drawModule.x}px;top: ${drawModule.y}px;width: ${drawModule.width}px;height: ${drawModule.height}px;background: ${drawModule.color};"></div>`;
            break;
        case 'image':
            /* 绘制图像 */
            qrHtml += `<img style="position: absolute;left: ${drawModule.x}px;top: ${drawModule.y}px;width: ${drawModule.width}px;height: ${drawModule.height}px;" src="${drawModule.imageSrc}" />`;
            break;
        }
    }
    document.getElementById('qrcode') = qrHtml;
    </script>
</body>
</html>
  • svg

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>uQRCode二维码生成</title>
    </head>
    <body>
    <svg id="qrcode" width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1"></svg>
    <script type="text/javascript" src="uqrcode.js"></script>
    <script>
    // 引入uQRCode
    var UQRCode = window.UQRCode;
    // 获取uQRCode实例
    var qr = new UQRCode();
    // 设置二维码内容
    qr.data = "https://uqrcode.cn/doc";
    // 设置二维码大小,必须与canvas设置的宽高一致
    qr.size = 200;
    // 设置二维码前景图,可以是路径
    qr.foregroundImageSrc =
        'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAC3xJREFUeJztnd1vFNcZxodSJ3y3EL7SYIQwu15wI5FSAkqVkISKgEkuSIEC6127RrloL9r8D4n5UFUZp/9C24A/okqUOzCmSdoohQtkXIkiRS1VC7YQF41Kbe/unL7PzHt2z45ndnZmd1l75hzrSSwzMzvn+c15z8ee3dcwdIlkWaRlqSnF62a+4dDiiMtZ36cKyc183NQ3WS2sZ2IqWX/phwTWEDhuEKT5S0hLSctJK1grWasiLllPWe9l7MUSowTJDU7oopKVICSEZXwz3yKtJj1HWkdaT9pA2hgTbeA6r2MPVrMnEpCEI8HU1FpUGC18cbQEPB1r+Ea+Q2olbSFtJbWREqxkxCXr2cZ1hwebSM+zN2vYq+XsXYtRQ2uRJ8hWgaa4kl8ET0Ur30SK9F3STtL3SLtJL5P2kPZGXHu4rru57vCgg9TO3mxir1azd0uNUmuRUALBWKzAAOm1pBcM+4nYwTeBG3uNtJ/0FukQqZP0NuudiErWr5PrfID0JulVwwb1Enu0lT1byx6qUKpqJWoH3qLAQIzcbNhNFU/CKwzhMOld0o9JaVKW1EP6CamXdDqi6uU69nCdUffjpCPsyZvs0U72bDN7KKHI8OULRcIAQcQ9NDXQRYhCeNpF2ocXPXjw4M8uX748eP/+/b9NT08/ETE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M36RK18n+GJEwNAYal3QAAAABJRU5ErkJggg==';
    // 调用制作二维码方法
    qr.make();
    
    var drawModules = qr.getDrawModules();
    // 遍历drawModules创建svg元素
    var qrHtml = '';
    for (var i = 0; i < drawModules.length; i++) {
        var drawModule = drawModules[i];
        switch (drawModule.type) {
        case 'tile':
            /* 绘制小块 */
            qrHtml += `<rect x="${drawModule.x}" y="${drawModule.y}" width="${drawModule.width}" height="${drawModule.height}" style="fill: ${drawModule.color};" />`;
            break;
        case 'image':
            /* 绘制图像 */
            qrHtml += `<image href="${drawModule.imageSrc}" x="${drawModule.x}" y="${drawModule.y}" width="${drawModule.width}" height="${drawModule.height}" />`;
            break;
        }
    }
    document.getElementById('qrcode') = qrHtml;
    </script>
    </body>
    </html>

更多用法大家自行探索咯,期待分享哟~

导出临时文件路径

原生方式基于Canvas的,请自行参阅各平台Canvas的导出方式。以下是部分示例:

  • uni-app

    // 通过uni.createCanvasContext方式创建绘制上下文的,对应导出API为uni.canvasToTempFilePath
    // 调用完ctx.draw()方法后不能第一时间导出,否则会异常,需要有一定的延时
    setTimeout(() => {
    uni.canvasToTempFilePath(
        {
            canvasId: this.canvasId,
            fileType: this.fileType,
            width: this.canvasWidth,
            height: this.canvasHeight,
            success: res => {
                console.log(res);
            },
            fail: err => {
                console.log(err);
            }
        }, 
        // this // 组件内使用必传当前实例
    );
    }, 300);
  • Canvas2D

    // 得到base64
    console.log(canvas.toDataURL());
    // 得到buffer
    console.log(canvas.toBuffer());

保存二维码到本地相册

必须在导出临时文件路径成功后再执行保存。uni-app通用保存方式(H5除外):

uni.saveImageToPhotosAlbum({
    filePath: tempFilePath,
    success: res => {
        console.log(res);
    },
    fail: err => {
        console.log(err);
    }
});

H5可以通过设置<a>标签href属性的方式进行保存:

const aEle = document.createElement('a');
aEle.download = 'uQRCode'; // 设置下载的文件名,默认是'下载'
aEle.href = tempFilePath;
document.body(aEle);
aEle.click();
aEle.remove(); // 下载之后把创建的元素删除

经过测试,PC端浏览器可以下载,部分安卓自带或第三方浏览器可以下载,安卓微信浏览器不适用,移动端iOS所有浏览器均不适用,差异较大,还是推荐各位导出文件给图片组件显示,然后提示用户通过长按图片进行保存这种方式。

uni-app组件方式

安装

通过uni-app插件市场地址安装:https://ext.dcloud.net.cn/plugin?id=1287。详细配置请移步到:文档 > uni-app组件

引入

uni-app默认为easycom模式,可直接键入<uqrcode>标签。

简单用法

安装uqrcode组件后,在template中键入<uqrcode/>。设置ref属性可使用组件内部方法,canvas-id属性为组件内部的canvas组件标识,value属性为二维码生成对应内容,options为配置选项,可配置二维码样式,绘制Logo等,详见:options

<uqrcode ref="uqrcode" canvas-id="qrcode" value="https://uqrcode.cn/doc" :options="{ margin: 10 }"></uqrcode>

导出临时文件路径

为了保证方法调用成功,请在 complete 事件返回success=true后调用。

// uqrcode为组件的ref名称
this.$refs.uqrcode.toTempFilePath({
  success: res => {
    console.log(res);
  }
});

保存二维码到本地相册

为了保证方法调用成功,请在 complete 事件返回success=true后调用。

// uqrcode为组件的ref名称
this.$refs.uqrcode.save({
  success: () => {
    uni.showToast({
      icon: 'success',
      title: '保存成功'
    });
  }
});

更多使用说明请前往官方文档查看:https://uqrcode.cn/doc

隐私、权限声明

1. 本插件需要申请的系统权限列表:

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

    "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

    "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

    "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

    "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

    "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

    "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

    "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

    "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

    "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

    "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

  2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

  3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

  4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

    (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and

    (b) You must cause any modified files to carry prominent notices stating that You changed the files; and

    (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and

    (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.

    You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

  5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

  6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

  7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

  8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

  9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

    END OF TERMS AND CONDITIONS

    APPENDIX: How to apply the Apache License to your work.

    To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.

    Copyright [yyyy] [name of copyright owner]

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问