We are gathering with people who want to develop teams and creating apps using Ruby on Rails and React. Since I was in charge of implementing the barcode reading function, I tried to make it roughly work.
rails _6.0.3_ new barcode_app -d postgresql
cd barcode_app
yarn add quagga
rails webpacker:install
rails webpacker:install:react
rails generate react:install
app/javascript/components/scanners/config.json
{
"inputStream": {
"type": "LiveStream",
"constraints": {
"width": { "min": 450 },
"height": { "min": 300 },
"facingMode": "environment",
"aspectRatio": { "min": 1, "max": 2 }
}
},
"locator": {
"patchSize": "medium",
"halfSample": true
},
"numOfWorkers": 2,
"frequency": 10,
"decoder": {
"readers": ["ean_reader"]
},
"locate": true
}
app/javascript/components/scanners/Index.jsx
import React, { useState } from "react";
import Scanner from "./Scanner";
const Index = () => {
const [camera, setCamera] = useState(true);
const [result, setResult] = useState(null);
const onDetected = result => {
setResult(result);
setCamera(!camera)
window.location.href = '/scanners/' + result
};
return (
<section className="section-wrapper">
<div className="section-title">
<h1 className="section-title-text">
{camera ? <Scanner onDetected={onDetected} /> : <p>Loading...</p> }
</h1>
</div>
</section>
);
}
export default Index
app/javascript/components/scanners/Scanner.jsx
import React, { useEffect } from "react";
import config from "./config.json";
import Quagga from "quagga";
const Scanner = props => {
const { onDetected } = props;
useEffect(() => {
Quagga.init(config, err => {
if (err) {
console.log(err, "error msg");
}
Quagga.start();
return () => {
Quagga.stop()
}
});
Quagga.onProcessed(result => {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(
0,
0,
Number(drawingCanvas.getAttribute("width")),
Number(drawingCanvas.getAttribute("height"))
);
result.boxes
.filter(function(box) {
return box !== result.box;
})
.forEach(function(box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, {
color: "green",
lineWidth: 2
});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, {
color: "#00F",
lineWidth: 2
});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(
result.line,
{ x: "x", y: "y" },
drawingCtx,
{ color: "red", lineWidth: 3 }
);
}
}
});
Quagga.onDetected(detected);
}, []);
const detected = result => {
onDetected(result.codeResult.code);
};
return (
<div id="interactive" className="viewport" />
);
};
export default Scanner;
https://github.com/visgl/react-map-gl/issues/874
config/webpack/environment.js
const { environment } = require('@rails/webpacker')
//Postscript
environment.loaders.delete('nodeModules');
module.exports = environment
GitHub https://github.com/yodev21/scanner_app
Try scanning barcodes in your browser using WebRTC
Recommended Posts