遇到以下问题:
来自服务器的条形码图像-> 将其实现到画布上,因此我周围有空白区域,以便使用 quagga.js 更好地定位-> 将结果保存到 base64 -> 使用结果并扫描出条形码数据。
我的代码如下所示:
const srcImage = document.querySelector('#src-image').src
const checkBarcode = document.querySelector('#barcode-check')
let dataURL
function addWhiteSpaceAroundImage(srcImage) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const image = new Image()
image.onload = drawImageActualSize
image.src = srcImage
function drawImageActualSize() {
const extraSpace = 100
canvas.width = this.naturalWidth + extraSpace * 2
canvas.height = this.naturalHeight + extraSpace * 2
ctx.fillStyle = '#FFFFFF'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(this, extraSpace, extraSpace)
dataURL = canvas.toDataURL('image/png') // <--- i need this dataURL for "decodeBarcode()"
}
}
function decodeBarcode(image) {
// TODO: here BASE64 Image from "addWhiteSpaceAroundImage()"
console.log(image)
return new Promise((resolve, reject) => {
Quagga.decodeSingle(
{
src: image,
locate: true,
decoder: {
readers: ['code_128_reader'],
},
},
function (result) {
if (result) {
resolve(result)
} else {
reject(new Error('no detection'))
}
}
)
})
}
decodeBarcode(dataURL) //<--- is undefined
这是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Reader Test</title>
<style>
body {
background-color: rgb(34, 34, 34);
text-align: center;
}
* {
margin: 20px 0;
}
</style>
</head>
<body>
<img id="src-image"
src="https://www.cognex.com/library/media/resources/symbologies/code128.jpg?h=250&w=447&la=de-AT&hash=4D254808A9954CB9CAD786F569BE0C78"
alt=""> <br>
<!-- <button onclick="addWhiteSpaceAroundImage('barcode_test.png')">Add Whitespace to
Image</button> <br> -->
<button id="barcode-check">Check Barcode</button> <br>
<img id="img-result" src="" alt="">
<script
src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>
<script src="app.js"></script>
</body>
</html>
我知道异步代码肯定有一些问题,但我不知道如何使它工作