Vue 中使用 Canvas 绘制二维码

在 vue 中使用 Canvas 绘制二维码可分为以下几个步骤:

  1. 安装 库:npm install qrcode --save

  2. 在 Vue 组件中导入 qrcode 库

    java 复制代码
    import QRCode from 'qrcode';
  3. 创建 Canvas 元素

  4. <canvas ref="canvas"></canvas>

    在 Vue 组件的生命周期钩子函数 mounted 中编写 Canvas 绘制二维码的代码

javascript 复制代码
mounted() {
  const canvas = this.$refs.canvas;
  const ctx = canvas.getContext('2d');
  QRCode.toDataURL('https://www.google.com', { errorCorrectionLevel: 'M' }, function(err, url) {
    if (err) throw err;
    const img = new Image();
    img.onload = function() {
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };
    img.src = url;
  });
},

在上面的代码中,我们使用 QRCode 库的 toDataURL 方法生成二维码图片的 base64 编码,并将其转换为 Image 对象,最后在 Canvas 上绘制
6. 样式要有吧

  1. canvas {

    width: 200px;

    height: 200px;

    border: 1px solid #ccc;

    }

  2. 完整的 Vue 组件代码 注意 注意 你们的二维码 码 和我不一样 记得转一下 再弄

javascript 复制代码
<template>
  <div>
    <canvas ref="canvas"></canvas>
  </div>
</template>
 
<script>
import QRCode from 'qrcode';
 
export default {
  mounted() {
    const canvas = this.$refs.canvas;
    const ctx = canvas.getContext('2d');
    QRCode.toDataURL('https://www.google.com', { errorCorrectionLevel: 'M' }, function(err, url) {
      if (err) throw err;
      const img = new Image();
      img.onload = function() {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      };
      img.src = url;
    });
  }
};
</script>
 
<style>
canvas {
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
}
</style>
相关推荐
KaMeidebaby5 小时前
卡梅德生物技术快报|骆驼纳米抗体:从原核表达、高通量测序到分子对接全流程实现
前端·数据库·其他·百度·新浪微博
子兮曰7 小时前
Node.js v26.1.0 深度解读:FFI、后量子密码与调试器的进化
前端·后端·node.js
测试员周周8 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
西洼工作室9 小时前
前端直传OSS服务端签名(Policy+Signature)/STS临时凭证
前端·文件上传·oss
你很易烊千玺9 小时前
日常练习-数组 字符串常用的场景
前端·javascript·字符串·数组
weixin1997010801610 小时前
[特殊字符] RESTful API 接口规范详解:构建高效、可扩展的 Web 服务(附 Python 源码)
前端·python·restful
存在的五月雨10 小时前
Vue3项目一些语法
前端·javascript·react.js
nashane11 小时前
HarmonyOS 6学习:Web组件同层渲染事件处理与智能长截图实现
前端·学习·harmonyos·harmonyos 5
大家的林语冰11 小时前
Node 2026 发布,JS 三大新功能上线,最后一个奇偶版本
前端·javascript·node.js