乐趣区

关于javascript:Vue3-Vant-jsQr-图片上传自动识别二维码

npm install jsqr --save
// utils/qrcode.js
import jsQR from "jsqr"

export const scanQrCode = (file, callback) => {const image = new Image()
  image.src = file.content
  image.addEventListener("load", (e) => {
    console.log(
      "image on load, image.naturalWidth, image.naturalHeight",
      image.naturalWidth,
      image.naturalHeight
    )

    const canvas = document.createElement("canvas") // Creates a canvas object
    canvas.width = image.naturalWidth // Assigns image's width to canvas
    canvas.height = image.naturalHeight // Assigns image's height to canvas

    const context = canvas.getContext("2d") // Creates a contect object
    context.imageSmoothingEnabled = false
    context.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight) // Draws the image on canvas

    const imageData = context.getImageData(0, 0, image.naturalWidth, image.naturalHeight) // Assigns image base64 string in jpeg format to a variable
    const code = jsQR(imageData.data, image.naturalWidth, image.naturalHeight)

    if (code) {console.log("Found QR code", code)

      callback(code)
    }
  })
}
// components/TestUploader.vue
<template>
      <van-uploader :after-read="afterRead"/>
</template>

<script setup>
import {scanQrCode} from "../utils/qrcode";

const afterRead = (file) => {scanQrCode(file, (code) => {console.log(code);
  });
};
</script>
退出移动版