Skip to content

QrCode ​

QrCode 在设备本地用 ZXing 生成二维码,不请求外网。适合支付扫码、分享链接。页面脚本和任务脚本都能用。

生成结果多为本地文件路径,交给 image 的 src 即可。

javascript
let path = QrCode.toFile('https://deeke.cn', { size: 400 });
方法作用
toFile(content) / (content, size) / (content, options)写到文件,返回路径
toBase64(content) / (content, size) / (content, options)纯 Base64
toDataUrl(content) / (content, size) / (content, options)data:image/...;base64,...
toBytes(content) / (content, options)图片字节数组

失败返回 null(内容为空、编码失败、写盘失败等)。

options ​

字段类型默认说明
size / width / heightnumber400边长 px(约 64–2048)
margin / quietZonenumber1四边静区(模块数)
level / errorCorrection / eccstring"M"纠错等级 L / M / Q / H
foreground / color / darkstring"#000000"前景色,#RGB 或 #RRGGBB
background / light / bgstring"#FFFFFF"背景色
format / typestring"png"png / jpg / jpeg / webp
qualitynumber100JPEG、WebP 质量 0–100
path / file / deststring缓存自动命名自定义输出绝对路径
fileUrlbooleanfalse为 true 时路径带 file:// 前缀
charset / encodingstring"UTF-8"内容字符集

toFile(content, options) ​

参数:

  • content {string} 要编码的文本(如支付宝当面付返回的 qrCode)
  • options {object|number} 可选。传数字时视为 size

返回: {string|null} 本地绝对路径;fileUrl: true 时为 file://...

javascript
let path = QrCode.toFile(payParams.qrCode, {
    size: 400,
    margin: 2,
    level: 'M',
    foreground: '#000000',
    background: '#FFFFFF',
    format: 'png'
});
if (!path) {
    this.toast('二维码生成失败');
    return;
}
this.setData({ qrImage: path });
json
{ "type": "image", "src": "{{qrImage}}", "fit": "contain", "style": { "width": 200, "height": 200 } }

toBase64(content, options) ​

返回: {string|null} 不带 data: 前缀的 Base64。

toDataUrl(content, options) ​

返回: {string|null} 如 data:image/png;base64,...,可给部分 WebView / 文档用。

toBytes(content, options) ​

返回: {byte[]|null} 压缩后的图片字节。

完整示例(支付扫码) ​

javascript
Page({
  onPayQr() {
    this.showLoading('生成二维码…');
    let res = /* 下单得到 payParams.qrCode */;
    this.hideLoading();
    let text = res.data.payParams.qrCode;
    let path = QrCode.toFile(text, { size: 440, margin: 1, level: 'M' });
    if (!path) {
      this.toast('二维码生成失败');
      return;
    }
    this.setData({
      qrOpen: true,
      qrImage: path,
      qrStatus: '请使用支付宝扫码'
    });
  }
});

在 DeekeScript Pro → 示例 → 接口 中可对照其它 API 展厅页;支付场景见业务 Demo。

注意 ​

  • 不要对 QrCode 使用 typeof;直接调用并用返回值判断成败。
  • 内容过长或纠错过高可能失败,可改用 level: 'L' 或缩短文本。
  • 默认写在应用缓存目录;需要长期保留时自己传 path。

相关 ​