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>
相关推荐
小满zs31 分钟前
Next.js第十六章(font字体)
前端·next.js
喝拿铁写前端5 小时前
别再让 AI 直接写页面了:一种更稳的中后台开发方式
前端·人工智能
A向前奔跑7 小时前
前端实现实现视频播放的方案和面试问题
前端·音视频
十一.3667 小时前
131-133 定时器的应用
前端·javascript·html
xhxxx8 小时前
你的 AI 为什么总答非所问?缺的不是智商,是“记忆系统”
前端·langchain·llm
3824278278 小时前
python:输出JSON
前端·python·json
2503_928411569 小时前
12.22 wxml语法
开发语言·前端·javascript
光影少年9 小时前
Vue2 Diff和Vue 3 Diff实现及底层原理
前端·javascript·vue.js
2501_946224319 小时前
旅行记录应用统计分析 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester