您的位置:

UniApp二维码生成详解

一、UniApp二维码生成海报

海报是一种非常流行的宣传方式。在UniApp中,我们可以利用uni-app-qrcode组件生成二维码再利用canvas生成海报。具体步骤如下:

1、为了保证海报生成的清晰度,我们需要在manifest.json文件中增加以下代码:

"mp-weixin": {
  "screenshot": {
    "borderRadius": "20px"
  }
}

2、在template中使用uni-app-qrcode生成二维码,并将其渲染至canvas中:

<template>
  <view>
    <canvas canvas-id="qrcode" class="qr-canvas"/>
  </view>
</template>

<script>
  import QRCode from '@/uni_modules/uni-app-qrcode/components/uni-app-qrcode/uni-app-qrcode.vue';

  export default {
    components: {
      QRCode
    },
    mounted() {
      this.draw();
    },
    methods: {
      draw() {
        const query = this.$root.$mp.query;
        uni.showToast({
          title: '海报生成中',
          icon: 'loading'
        });
        let qrcanvas = uni.createCanvasContext('qrcode', this);
        let canvasWidth = 375;
        let canvasHeight = 667;
        let qrcodeWidth = 200;
        let x = (canvasWidth - qrcodeWidth) / 2;
        qrcanvas.drawImage('/static/logo.png', x, 160, qrcodeWidth, qrcodeWidth);
        qrcanvas.draw(false, () => {
          uni.canvasToTempFilePath({
            canvasId: 'qrcode',
            success: (res) => {
              let qrSrc = res.tempFilePath;
              this.drawPoster(qrSrc);
            }
          }, this);
        }, this);
      },
      drawPoster(qrSrc) {
        // 生成海报内容
        let poster = uni.createCanvasContext('poster', this);
        let canvasWidth = 375;
        let canvasHeight = 667;
        poster.setFillStyle('#f3f3f3');
        poster.fillRect(0, 0, canvasWidth, canvasHeight);
        poster.drawImage('/static/bg.jpg', 0, 0, canvasWidth, 400);
        poster.save();
        poster.beginPath();
        poster.arc(70, 350, 35, 0, 2*Math.PI);
        poster.clip();
        poster.drawImage('/static/avatar.png', 35, 315, 70, 70);
        poster.restore();
        poster.setFontSize(16);
        poster.fillText('海报标题', 100, 340);
        poster.fillText('海报内容', 100, 360);
        poster.drawImage(qrSrc, 230, 410, 100, 100);
        poster.draw(true, () => {
          uni.canvasToTempFilePath({
            canvasId: 'poster',
            success: (res) => {
              this.posterSrc = res.tempFilePath;
              uni.hideToast();
            }
          }, this);
        }, this);
      }
    }
  }
</script>

二、UniApp生成小程序二维码

在UniApp中,我们可以使用uni.request接口调用微信提供的API生成小程序二维码。具体步骤如下:

1、首先,在manifest.json文件中声明需要使用uni.request接口的url地址:

{
  "mp-weixin": {
    "request": {
      "url": "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
    }
  }
}

2、在uni-app中引入uni.request,编写生成小程序二维码的代码:

<template>
  <image :src="image" />
</template>

<script>
  export default {
    data() {
      return {
        image: ''
      };
    },
    mounted() {
      this.getQRCode();
    },
    methods: {
      async getQRCode() {
        let res = await uni.request({
          url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit',
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + accessToken
          },
          data: {
            "scene": "123",
            "width": 280,
            "auto_color": false,
            "line_color": {"r":"0","g":"0","b":"0"},
            "is_hyaline": false
          },
          responseType: 'arraybuffer'
        });
        let base64 = uni.arrayBufferToBase64(res.data);
        this.image = 'data:image/jpeg;base64,' + base64;
      }
    }
  }
</script>

三、UniApp生成带信息的二维码

生成带信息的二维码,可以使用uni-app-qrcode组件。具体步骤如下:

1、在template中使用uni-app-qrcode生成带信息的二维码:

<template>
  <view>
    <qr-code content="{{ content }}" :size="300" :mode="mode" :margin="margin" :background="background" :foreground="foreground"></qr-code>
  </view>
</template>

<script>
  import QRCode from '@/uni_modules/uni-app-qrcode/components/uni-app-qrcode/uni-app-qrcode.vue';

  export default {
    components: {
      QRCode
    },
    data() {
      return {
        content: 'https://www.baidu.com',
        mode: 'square',
        margin: 4,
        background: '#ffffff',
        foreground: '#000000'
      };
    }
  }
</script>

四、UniApp长按识别二维码

为了方便用户识别二维码,我们可以通过长按来触发手机的识别功能。具体步骤如下:

1、在template中使用uni-longtap指令绑定长按事件:

<template>
  <image :src="qrCode" uni-longtap="previewQrCode" />
</template>

<script>
  export default {
    data() {
      return {
        qrCode: '/static/qrcode.jpg'
      };
    },
    methods: {
      previewQrCode() {
        uni.previewImage({
          urls: [this.qrCode]
        });
      }
    }
  }
</script>

五、UniApp生成二维码图片

在UniApp中使用uni-app-qrcode组件生成二维码图片非常简单。

1、在template中使用uni-app-qrcode生成二维码图片:

<template>
  <qr-code content="{{ content }}" :size="300" :mode="mode" :margin="margin" :background="background" :foreground="foreground" @imageLoad="onImageLoad" />
</template>

<script>
  import QRCode from '@/uni_modules/uni-app-qrcode/components/uni-app-qrcode/uni-app-qrcode.vue';

  export default {
    components: {
      QRCode
    },
    data() {
      return {
        content: 'https://www.baidu.com',
        mode: 'square',
        margin: 4,
        background: '#ffffff',
        foreground: '#000000'
      };
    },
    methods: {
      onImageLoad(e) {
        uni.saveImageToPhotosAlbum({
          filePath: e.detail.path,
          success: () => {
            uni.showToast({
              title: '保存成功'
            });
          },
          fail: () => {
            uni.showToast({
              title: '保存失败'
            });
          }
        });
      }
    }
  }
</script>

六、UniApp识别二维码

其中一种识别二维码的方式是使用uni.scanCode,在UniApp中非常简单。

1、在template中添加触发识别二维码的按钮:

<template>
  <button type="primary" @click="scanQRCode">扫描二维码</button>
</template>

<script>
  export default {
    methods: {
      scanQRCode() {
        uni.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            uni.navigateTo({
              url: res.result
            });
          }
        });
      }
    }
  }
</script>

七、UniApp生成二维码海报

最后,我们可以将UniApp二维码生成和海报生成结合起来,生成二维码海报。具体步骤如下:

1、在template中使用uni-app-qrcode生成二维码,并将其渲染至canvas中:

<template>
  <view>
    <canvas canvas-id="qrcode" class="qr-canvas"/>
  </view>
</template>

<script>
  import QRCode from '@/uni_modules/uni-app-qrcode/components/uni-app-qrcode/uni-app-qrcode.vue';

  export default {
    components: {
      QRCode
    },
    mounted() {
      this.draw();
    },
    methods: {
      draw() {
        const query = this.$root.$mp.query;
        uni.showToast({
          title: '正在生成海报',
          icon: 'loading'
        });
        let qrcanvas = uni.createCanvasContext('qrcode', this);
        let canvasWidth = 375;
        let canvasHeight = 667;
        let qrcodeWidth = 200;
        let x = (canvasWidth - qrcodeWidth) / 2;
        qrcanvas.drawImage('/static/logo.png', x, 160, qrcodeWidth, qrcodeWidth);
        qrcanvas.draw(false, () => {
          uni.canvasToTempFilePath({
            canvasId: 'qrcode',
            success: (res) => {
              let qrSrc = res.tempFilePath;
              this.drawPoster(qrSrc);
            }
          }, this);
        }, this);
      },
      drawPoster(qrSrc) {
        // 生成海报内容
        let poster = uni.createCanvasContext('poster', this);
        let canvasWidth = 375;
        let canvasHeight = 667;
        poster.setFillStyle('#f3f3f3');
        poster.fillRect(0, 0, canvasWidth, canvasHeight);
        poster.drawImage('/static/bg.jpg', 0, 0, canvasWidth, 400);
        poster.save();
        poster.beginPath();
        poster.arc(70, 350, 35, 0, 2*Math.PI);
        poster.clip();
        poster.drawImage('/static/avatar.png', 35, 315, 70, 70);
        poster.restore();
        poster.setFontSize(16);
        poster.fillText('海报标题', 100, 340);
        poster.fillText('海报内容', 100, 360);
        poster.drawImage(qrSrc, 230, 410, 100, 100);
        poster.draw(true, () => {
          uni.canvasToTempFilePath({
            canvasId: 'poster',
            success: (res) => {
              uni.hideToast();
              this.posterSrc = res.tempFilePath;
            }
          }, this);
        }, this);
      }
    }
  }
</script>

八、UniApp如何生成二维码

通过上面的几个例子,我们已经了解了UniApp如何生成二维码。简单总结如下:

1、使用uni-app-qrcode组件,可以方便地生成二维码;

2、使用uni.request接口,可以调用微信提供的API生成小程序二维码;

3、在canvas中使用uni-app-qrcode组件,可以生成带信息的二维码,并将其加入到海报中;

4、通过长按事件,可以触发手机的识别功能,方便用户识别二维码;

5、使用uni.scanCode接口,可以实现扫描二维码的功能;

6、最后,我们将生成的二维码加入到海报中,生成一张精美的二维码海报。