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>
相关推荐
念念不忘 必有回响1 小时前
nginx前端部署与Vite环境变量配置指南
前端·nginx·vite
JIngJaneIL2 小时前
篮球论坛|基于SprinBoot+vue的篮球论坛系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·篮球论坛系统
程序猿阿伟3 小时前
《首屏加载优化手册:Vue3+Element Plus项目提速的技术细节》
前端·javascript·vue.js
麦麦大数据4 小时前
D030知识图谱科研文献论文推荐系统vue+django+Neo4j的知识图谱|论文本文相似度推荐|协同过滤
vue.js·爬虫·django·知识图谱·科研·论文文献·相似度推荐
尘觉4 小时前
面试-浅复制和深复制?怎样实现深复制详细解答
javascript·面试·职场和发展
fruge5 小时前
Vue Pinia 状态管理实战指南
前端·vue.js·ubuntu
绝无仅有5 小时前
某教育大厂面试题解析:MySQL索引、Redis缓存、Dubbo负载均衡等
vue.js·后端·面试
sean5 小时前
开发一个自己的 claude code
前端·后端·ai编程
用户21411832636025 小时前
dify案例分享-用 Dify 一键生成教学动画 HTML!AI 助力,3 分钟搞定专业级课件
前端
chxii6 小时前
ISO 8601日期时间标准及其在JavaScript、SQLite与MySQL中的应用解析
开发语言·javascript·数据库