カメラにバーコードを写してください。
<input id="code" type="text">
<button id="btn">カメラでバーコードを読み込む</button>
<div id="modal" class="modal">
<div id="interactive" class="viewport"></div>
<p class="text">カメラにバーコードを写してください。</p>
</div>
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
}
h1 {
font-size: 1rem;
}
input {
width: 300px;
margin-bottom: 1rem;
font-size: 2rem;
}
.modal {
display: none;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
}
.text {
position: fixed;
bottom: 1rem;
left: 0;
width: 100%;
margin-top: 1rem;
color: #fff;
text-align: center;
}
const btn = document.getElementById('btn');
const modal = document.getElementById('modal');
btn.addEventListener('click', () => {
modal.style.display = 'block';
document.body.style.overflow = 'hidden';
Quagga.init(
{
inputStream: {
type: 'LiveStream',
constraints: {
width: window.innerWidth
},
},
decoder: {
readers: [
{
format: 'ean_reader',
config: {},
},
],
},
},
(err) => {
if (!err) {
Quagga.start();
} else {
modal.style.display = 'none';
document.body.style.overflow = '';
Quagga.stop();
alert(
'この機能を利用するには\nブラウザのカメラ利用を許可してください。'
);
}
}
);
});
Quagga.onDetected((result) => {
const code = result.codeResult.code;
if (/^4[5|9]/.test(code)) {
document.getElementById('code').value = code;
modal.style.display = 'none';
document.body.style.overflow = '';
Quagga.stop();
}
});