共计 1130 个字符,预计需要花费 3 分钟才能阅读完成。
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>
正文完
发表至: javascript
2022-07-15