SoFunction
Updated on 2025-03-10

Using Canvas to draw QR codes in Vue

Using Canvas to draw a QR code in Vue can be divided into the following steps:

Install the qrcode library:npm install qrcode --save

Importing qrcode libraries in Vue components

import QRCode from 'qrcode';

Create Canvas elements

<canvas ref="canvas"></canvas>

Write code to draw QR code in the life cycle hook function mounted of Vue component

mounted() {
  const canvas = this.$;
  const ctx = ('2d');
  ('', { errorCorrectionLevel: 'M' }, function(err, url) {
    if (err) throw err;
    const img = new Image();
     = function() {
      (img, 0, 0, , );
    };
     = url;
  });
},

In the above code, we use the toDataURL method of the QRCode library to generate the base64 encoding of the QR code image, convert it into an Image object, and finally draw it on Canvas.

Style settings

canvas {
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
}

Depending on the page's needs, you can set styles such as width, height and border of the Canvas element.

The complete Vue component code is as follows:

<template>
  <div>
    <canvas ref="canvas"></canvas>
  </div>
</template>
 
<script>
import QRCode from 'qrcode';
 
export default {
  mounted() {
    const canvas = this.$;
    const ctx = ('2d');
    ('', { errorCorrectionLevel: 'M' }, function(err, url) {
      if (err) throw err;
      const img = new Image();
       = function() {
        (img, 0, 0, , );
      };
       = url;
    });
  }
};
</script>
 
<style>
canvas {
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
}
</style>

This is the end of this article about using Canvas to draw QR codes in Vue. For more related content on Vue Canvas to draw QR codes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!