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>
相关推荐
踩着两条虫28 分钟前
AI + 低代码实战 | 一文吃透 API 管理、Swagger 导入与全局配置
前端·低代码·ai编程
AI自动化工坊29 分钟前
T3 Code:专为AI编程代理设计的Web IDE技术实践指南
前端·ide·人工智能·ai编程·t3
梦梦代码精33 分钟前
LikeShop 深度测评:开源电商的务实之选
java·前端·数据库·后端·云原生·小程序·php
Mr.E534 分钟前
odoo18 关闭搜索框点击自动弹出下拉框
开发语言·前端·javascript·odoo·owl·odoo18
鹏程十八少37 分钟前
4. 2026金三银四 Android OkHttp 面试核心 45 问:从源码到架构深度解析
android·前端·面试
invicinble39 分钟前
前端技术栈--webpack
前端·webpack·node.js
天籁晴空42 分钟前
微信小程序 静默登录 + 授权登录 双模式配合的设计方案
前端·微信小程序·uni-app
|晴 天|44 分钟前
Vue 3 博客 SEO 优化:Meta 标签、Sitemap、Schema.org 实战
前端·vue.js·dreamweaver
Apple_羊先森44 分钟前
# MOSS-TTS-Nano 教程 02:CLI 与 Web Demo 实战
前端·人工智能
Bat U1 小时前
JavaEE|多线程(三)
java·前端·java-ee