preface

A recent company business scenario has a need to generate and identify qr codes. Generate two-dimensional code before have done, choose qrcode.js this front-end library, the operation is relatively simple. I won’t repeat it here. At the beginning of the two-dimensional identification requirements feel very simple, think there is a corresponding front-end library directly used on the line. But when you actually start writing functionality, it turns out that two-dimensional recognition involves a lot of other functionality. Without further ado, let’s see how it works.

The implementation process

  • Call the camera

    Calling the camera from the browser already has a property in H5 that is compatible with most platforms. navigator.getUserMedia = navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.. mozGetUserMedia; . We’ll look at the MDN introduced: MediaDevices getUserMedia () will prompt the user for permission to use the media input media input will produce a MediaStream, containing the request of the media type of orbit. This stream can include A video track (from hardware or virtual video sources, such as cameras, video capture devices, screen sharing services, and so on), an audio track (also from hardware or virtual audio sources, such as microphones, A/D converters, and so on), or other track types. It returns a Promise object and on success a resolve callback to a MediaStream object. If the user refuses permission, or the required media source is not available, the promise rejects a PermissionDeniedError or NotFoundError. View the details which means that in the return value of this property we can get the stream of video that the camera is shooting.

  • The video stream is already available through getUserMedia and then we need to put it in video:

let option = {
                    width: 1280,
                    height: 720
                }
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                            navigator.mediaDevices.getUserMedia({
                                video: option
                            }).then(function(stream) {// play the video stream in real time in video self.$refs.video.srcObject = stream
                                self.$refs.video.style.display = 'block'// Capture the video contentsetTimeout(() => {
                                    self.screenShot()
                                }, 2000);
                            }).catch(function(err) {
                                alert(err);
                            });
                } else if (navigator.getUserMedia) {
                    navigator.getUserMedia({
                        video: true
                    }).then(function(stream) {
                        self.$refs.video.srcObject = stream
                        self.$refs.video.style.display = 'block'
                        setTimeout(() => {
                            self.screenShot()
                        }, 2000);
                    }).catch(function(err) {
                        alert(err);
                    });
                }
Copy the code
  • Canvas implementation screenshot

When the video is displayed normally, we can take screenshots in real time. b

                let $canvas = $('canvas');
                let $video = $('video');
                $canvas.attr({
                    width: $video.width(),
                    height: $video.height(),
                })
                let ctx = $canvas[0].getContext('2d');
                ctx.drawImage($video[0], 0, 0, $video.width(), $video.height());
                let base64 = $canvas[0].toDataURL('images/png'); This.decodeqrcode (base64) this.decodeqrcode (base64)Copy the code
  • Image recognition (to determine whether it is a QR code)

Use the QR code recognition library reqrcode.js to identify the captured video images, and if it fails, continue to capture and re-identify


decodeQrcode(base64) {
                let self = this
                // $('#screenshot_img').attr('src', base64)
                qrcode.decode(base64)
                qrcode.callback = function(imgMsg) {
                    if(! self.visible) {return
                    }
                    if (imgMsg == 'error decoding QR Code') {
                        setTimeout(functionScreenShot () {self.screenshot ()}, 2000)}else {
                        alert(imgMsg)
                        window.location.href = imgMsg
                    }
                }
                // }
            }
Copy the code
  • Get identification

The content of qr code is successfully obtained

conclusion

In the end, although the TWO-DIMENSIONAL code function was realized, it took much longer than I expected. The reason is that the two-dimensional code recognition is not only needed to recognize the two-dimensional code. Before recognition, we need to implement JavaScript call camera function, Canvas screenshot function and a series of problems. So the next time you encounter a demand that you have not contacted, you need to have a full investigation and detailed analysis of the difficulties of the demand.