莫方教程网

专业程序员编程教程与实战案例分享

微信小程序前端根据内容生成二维码Qrcode

在微信小程序开发项目中,后端返回的api接口数据中,有一个支付页面,这个支付页面网址在小程序中是打不开的,需要生成二维码让客户扫描支付,客户扫描二维码就会打开支付页面,支付项目金额!

1、需要下载封装好的qrcode的js文件,下载地址:夸克网盘分享

2、在我们需要在使用的页面将qrcode.js文件引入

import * as QRCode from '../../utils/qrcode.js'

3、首先微信小程序wxml文件中写入canvas标签

4、如果有中文的话,需要一个方法来解决中文乱码的问题(没有可不写)

  toUtf8(str) { //解决中文乱码的问题
    var out, i, len, c;
    out = "";
    len = str.length; //文本域值的长度
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i); //返回值是UTF-16的代码单元值 0-65535之间的整数 参数:大于等于0(如果小于0或者等于大于字符串的长度 则返回nan)
      // console.log('cc',c);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        out += str.charAt(i); // 从一个字符串中返回指定的字符
        // console.log('out',out); //就是文本域的值
      } else if (c > 0x07FF) {
        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      } else {
        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      }
    }
    return out;
  },

5、 获取可使用屏幕的宽高度的方法(px)

// 获取可使用窗口的框高度
getWindowWH(){
    var seeWH = {} // 往seeWH对象中新增窗口宽高度两个属性
    try {
        const res = wx.getSystemInfoSync()// 获取设备信息
        var w = res.windowWidth / (750 / 450) //可使用窗口的宽度
        var h = res.windowWidth / (750 / 450) //可使用窗口的高度
        seeWH.w = w
        seeWH.h = h
    } catch (e) {
        // Do something when catch error
        console.log('获取设备信息失败', e);
    }

    return seeWH
},

6、创建画布的方法

// 创建画布 接收传递过来的几个实参
drawCanvas(e,n,t,i){
    var that=this
    // e:代表文本域的值
    // n:canvasID
    // t:可使用窗口的宽度
    // i:可使用窗口的高度
    // that.data.bgVal:背景颜色 默认:#fff
    // that.data.clVal :前景颜色 默认:#000
    //这里的  drawQrcode.api.draw 是引入封装好的js文件进来里面 的 draw方法
    QRCode.api.draw(e,n,t,i,"","", that.data.bgVal, that.data.clVal)
},

7、 用画布内容区域生成导出一个指定的大小图片 的方法

createImage(){
    var that = this
    wx.canvasToTempFilePath({
        canvasId:"myCanvas", //必选
        success(res){
            // 生成好了关闭loading效果
            wx.hideLoading()
            console.log(res.tempFilePath)
        }
    })
},

8、点击生成二维码按钮事件

 // 点击生成二维码
  createQRCode() {
    var that=this
      // 有文本域的值 提示loading效果
      wx.showLoading({
        title: "生成中"
      })
      // 获取可使用宽高度
     let obj= that.getWindowWH()
      // 调用创建画布的方法,传递参数
      that.drawCanvas('https://www.vipshare8.com/', "myCanvas", obj.w, obj.h)
      setTimeout(()=>{
        //调用 把当前画布内容导出生成指定大小的图片
        that.createImage()
      },300)
    }
  },
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言