In the era of digitalization, QR code has penetrated into every aspect of our life. From mobile payment to product traceability, QR code has become an important carrier of information transfer due to its convenience and efficiency. With the continuous development of front-end technology, we can even use JavaScript to realize the QR code scanning function on the web page, providing users with a more convenient operation experience.
This article will take you on an in-depth look at how to use JavaScript to call the camera in conjunction with thejsQR
library, and how to control the flash, culminating in a fully functional web sweeping application.
I. Project overview
We will create a simple web application that is capable of:
- Call the device camera to get a live video stream.
- Creates a scanning area on a web page where users can place QR codes to be scanned.
- utilization
jsQR
The library decodes the QR code image data in the scanning area and obtains the content of the QR code. - Provides the ability to manually enter the content of the QR code.
- If supported by the device, you can also control the flash on/off for scanning in low light conditions.
II. Steps towards realization
1. HTML structure
First, we need to build the basic HTML structure, including:
-
<video>
Label: used to display the live video stream captured by the camera. -
<canvas>
Tabs: used to draw video frames and scanning areas and get image data from them. -
<div>
Tags: used to create UI elements such as scan areas, button groups, etc.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sweep</title>
<link rel="stylesheet" href="">
</head>
<body>
<video autoplay></video>
<canvas hidden></canvas>
<div class="scan-area"></div>
<div class="btn-group">
<button >manual input</button>
<button >flash bulb (photography)</button>
</div>
<script src="/npm/[email protected]/dist/"></script>
<script src=""></script>
</body>
</html>
2. CSS styles
To enhance the user experience, we need to add some styles to the page elements:
/* */
body {
margin: 0;
overflow: hidden;
}
#video {
width: 100%;
height: auto;
display: block;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.scan-area {
border: 3px solid yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
height: 30%;
}
/* ...Other styles */
3. JavaScript interaction
JavaScript code is the core part to realize the code scanning function, which includes the following steps:
-
Get camera permissions: Use the
()
method requests access to the user's camera. -
Play video stream: Assigns the fetched video stream to the
<video>
tabbedsrcObject
property and call the()
method to start playback. -
Creating a Scan Loop: Use the
requestAnimationFrame()
method creates a loop that continuously acquires frame images from the video stream and performs QR code decoding. -
Draw video frames: In each frame, use the
()
method draws the video frame to the<canvas>
Element on. -
Acquire image data of the scanned area: Use the
()
method acquires the image data of the scanned area. -
Decode the QR code: Use
jsQR
librariesjsQR()
method decodes the image data, and if the decoding is successful, the content of the QR code is obtained. -
Processing of scanning results: Processing of the decoded QR code content, such as jumping to links, displaying information, etc.
-
Realization of other functions: Realization of manual input of QR code content and control of flash, etc.
//
const video = ('video');
const overlay = ('overlay');
const manualInputBtn = ('manualInputBtn');
const flashBtn = ('flashBtn'); const scanArea = ('.
const scanArea = ('.scan-area');
const scanArea = ('.scan-area'); let stream
const scanArea = ('.scan-area'); let stream; let scanning = false;
let flashEnabled = false;
// Get camera permissions and start streaming video
({ video: { facingMode: "environment" } })
.then(s => {
stream = s; }
= stream.
();
// Start scanning
scanning = true; requestAnimationFrame(scan); // Start scanning.
requestAnimationFrame(scan); // Start scanning.
})
.catch(err => {
("Unable to access camera:", err); }); {
});
// Scan the QR code
function scan() {
if (scanning) {
const canvas = ('2d'); const videoWidth = ;; // Scan the QR code.
const videoWidth = ;
const videoHeight = ;
// Set the canvas size
const videoWidth = ;const videoHeight = ; // Set the size of the canvas.
= videoHeight.
// Draw the video frame to the canvas
(video, 0, 0, videoWidth, videoHeight);
// ... Getting the scanned area image data
// Decode the QR code using the jsQR library.
const code = jsQR(, , );
// If the code is successfully decoded, stop scanning and process the result
if (code) {
scanning = false; handleScanResult(); handleScanResult()
handleScanResult();
} else {
requestAnimationFrame(scanning); }
}
}
}
// Handle the scan result
function handleScanResult(data) {
function handleScanResult(data) { alert("Scan result: " + data); handleScanResult(data); handleScanResult(data); } }
// This is where you can perform actions based on the scan result, such as jumping to a link or displaying a message.
}
// Manually enter the button click event
('click', function() {
// ...
});
// Flash button click event
('click', function() {
// ...
});
III. Summary
With the above steps, we have successfully implemented the QR code scanning function on the web side using JavaScript. This function can be widely used in various scenarios, for example:
- Mobile Payment: Users can use their cell phone to scan the QR code on the webpage to complete the payment.
- Product Traceability: Users can scan the QR code on the product to view the product information, date of production, logistics information, etc.
- Event Check-In: Users can scan the QR code with their cell phone to complete the event check-in.
As Web technology continues to evolve, I believe more innovative application scenarios will emerge in the future.
I hope this article can help you understand the realization principle of the webpage code scanning function, and inspire your interest in exploring more front-end black technology.