Taro小程序微信、支付宝双端实现二维码图片生成

一、安装依赖

这里安装1.5.3以下版本,最新的会报错

ReferenceError: TextEncoder is not defined at new ByteData (byte-data.js:6:1) at buildSingleSegment (segments.js:262:1

bash 复制代码
npm install qrcode@1.5.3 --save

weapp-qrcode-canvas-2d仅支持微信小程序

bash 复制代码
npm install weapp-qrcode-canvas-2d --save

仅供参考:我使用的版本如下:

bash 复制代码
"qrcode": "1.5.3",
"vue": "^3.0.0",
"weapp-qrcode-canvas-2d": "^1.1.6"

二、具体实现

1、封装个QRCode.vue子组件

javascript 复制代码
<template>
  <view class="qrcode-container">
    <!-- 
        1. 用于绘制的隐藏 Canvas
        type="2d" 和 id 是关键
      -->
    <canvas
      id="myCanvas"
      type="2d"
      :style="{
        width: `${width}px`,
        height: `${height}px`,
        position: 'fixed',
        left: '9999px', // 移出屏幕可视区
        top: '-9999px',
      }"
    />
    <!-- 
        2. 最终展示给用户的图片
        show-menu-by-longpress 属性支持长按保存
      -->
    <image
      v-if="qrCodeUrl"
      :src="qrCodeUrl"
      :style="{
        width: `${width}px`,
        height: `${height}px`,
      }"
      mode="aspectFit"
      show-menu-by-longpress
      @click="saveToAlbum"
    />
  </view>
</template>
  
  <script setup>
import { ref, onMounted, nextTick } from "vue";
import Taro from "@tarojs/taro";
import drawQrcode from "weapp-qrcode-canvas-2d";
import QRCode from 'qrcode';

const props = defineProps({
  // 要生成二维码的文本或链接
  text: {
    type: String,
    required: true,
  },
  width: {
    type: Number,
    default: 200,
  },
  height: {
    type: Number,
    default: 200,
  },
});

const qrCodeUrl = ref(""); // 存储二维码的临时图片路径

// 生成二维码的核心函数-weapp
const generateWxQRCode = () => {
  const query = Taro.createSelectorQuery();
  // 获取 Canvas 节点
  query
    .select("#myCanvas")
    .fields({ node: true, size: true })
    .exec((res) => {
      if (!res || !res[0]) {
        console.error("Canvas 节点获取失败");
        return;
      }

      const canvas = res[0].node;
      // 调用库的方法在 Canvas 上绘制二维码
      drawQrcode({
        canvas,
        canvasId: "myCanvas",
        width: props.width,
        height: props.height,
        text: props.text,
        background: "#ffffff", // 背景色,可自定义
        foreground: "#000000", // 前景色(二维码颜色)
      });

      // 将 Canvas 内容转换为临时图片路径,便于展示和保存
      setTimeout(() => {
        Taro.canvasToTempFilePath({
          canvasId: "myCanvas",
          canvas,
          x: 0,
          y: 0,
          width: props.width,
          height: props.height,
          destWidth: props.width * 2, // 输出图片宽度,*2可使图片更清晰
          destHeight: props.height * 2, // 输出图片高度
          success(res) {
            qrCodeUrl.value = res.tempFilePath;
          },
          fail(err) {
            console.error("Canvas 转图片失败", err);
          },
        });
      }, 100); // 延迟确保二维码绘制完成
    });
};
// Base64编码函数(小程序兼容)
const base64Encode = (str) => {
  if (typeof btoa !== 'undefined') {
    return btoa(str); // 浏览器环境
  } else {
    // 小程序环境使用 Buffer 或 Taro API
    try {
      if (typeof Buffer !== 'undefined') {
        return Buffer.from(str).toString('base64');
      } else {
        // 使用 Taro 的 base64 编码
        return Taro.base64.encode(str);
      }
    } catch (error) {
      console.error('Base64编码失败:', error);
      return '';
    }
  }
};

// 生成二维码的核心函数-aliapy
const createAlipayQrCode = async () => {
  try {
    // 生成 SVG 格式的二维码
    const svgString = await QRCode.toString(props.text, { type: 'svg' });
    
    // 使用兼容的Base64编码
    const base64SVG = base64Encode(svgString);
    const imgSrc = `data:image/svg+xml;base64,${base64SVG}`;
    
    qrCodeUrl.value = imgSrc;
  } catch (error) {
    console.error('SVG二维码生成失败:', error);
  }
};
const generateQRCode = () => {
  // 根据环境选择二维码生成方法
  const env = Taro.getEnv();
  if (env === Taro.ENV_TYPE.WEAPP) {
    generateWxQRCode();
  } else if (env === Taro.ENV_TYPE.ALIPAY) {
    setTimeout(() => {
      createAlipayQrCode(); 
    }, 100);
  }
}
// 组件挂载时生成二维码
onMounted(() => {
  nextTick(() => {
    generateQRCode();
  });
});
</script>
  
<style lang="scss">
.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

2、在父组件你需要的地方使用即可

javascript 复制代码
 <QRcode :text="qrCodeUrl" :size="200"></QRcode>

本来是想问ai的结果豆包只会编造不存在的插件和api ,麻了。。。。。

end!

希望记录的问题能帮助到你~

相关推荐
程序鉴定师11 小时前
深圳小程序公司推荐 助力企业数字化转型优质服务商
大数据·小程序
陪小甜甜赏月15 小时前
微信小程序分享onShareAppMessage
前端·微信小程序·小程序
weikecms17 小时前
本地生活 CPS 返利小程序搭建,支持外卖 + 出行 + 加油 + 酒店
小程序·生活
AI砖家1 天前
微信小程序包体积优化与分包实战:从2M困境到优雅突破
微信小程序·小程序·notepad++·分包·小程序体积压缩
2501_915918412 天前
Linux 上生成 AppStoreInfo.plist,App Store 上架 iOS
android·ios·小程序·https·uni-app·iphone·webview
爱学习的程序媛2 天前
微信小程序3D开发框架技术对比:XR-Frame与threejs-miniprogram
3d·微信小程序·小程序·前端框架
万岳科技系统开发2 天前
外卖系统小程序开发方案解析:直播、团购与外卖功能如何融合
数据库·小程序·架构
小羊Yveesss2 天前
2026年微信小程序开发教程
微信小程序·小程序·notepad++
万岳科技程序员小赵2 天前
同城外卖系统开发:APP、小程序上线前需要准备什么?
小程序·同城外卖系统·同城外卖系统app开发
肖有米XTKF86462 天前
肖有米开发团队:推三返一模式系统开发-推三返一商业平台小程序介绍
人工智能·小程序·团队开发·csdn开发云