In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use Vue to achieve browser-side code scan function". In daily operation, I believe many people have doubts about how to use Vue to achieve browser-side code scan function. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "how to use Vue to achieve browser-side code scan function". Next, please follow the editor to study!
Realize the effect
In this example, there are mainly two pages: the front page and the code scanning page, and the specific implementation effect is shown in the following figure.
Home page: click the SCAN QRCODE button to go to the scan page.
Scan the code page: when you enter for the first time, or pop up the system prompt box for obtaining camera access, click allow access, and the page begins to load camera data and start QR code capture and pickup. If the QR code is captured, start QR code parsing. After successful parsing, load the recognition success pop-up window.
Online experience: https://dragonir.github.io/h6-scan-qrcode
Tip: vertical screen access is required in a browser with a camera device. The little knowledge of mobile phone horizontal and vertical screen detection can be found in my other article, "Front-end knowledge in 50-tone Mini Game".
Technical introduction WebRTC API
WebRTC (Web Real-Time Communications) is a real-time communication technology, which allows network applications or sites to establish a point-to-point (Peer-to-Peer) connection between browsers without the aid of an intermediary, so as to realize the transmission of video stream and / or audio stream or other arbitrary data. These standards included in WebRTC make it possible for users to create point-to-point (Peer-to-Peer) data sharing and conference calls without installing any plug-ins or third-party software.
Three main interfaces:
MediaStream: the synchronous stream of video and audio can be obtained through the camera and microphone of the device.
RTCPeerConnection: a component used by WebRTC to build stable and efficient streaming between point to point.
RTCDataChannel: allows browsers to establish a high-throughput, low-latency channel for transmitting arbitrary data.
? Go to MDN for further study: WebRTC_API
WebRTC adapter
Although the WebRTC specification is relatively robust, not all browsers implement all of its functions, and some browsers need to add prefixes to some or all of the WebRTC API in order to work properly.
The WebRTC organization provides a WebRTC adapter (WebRTC adapter) on github to solve the compatibility problem of implementing WebRTC on different browsers. This adapter is a JavaScript gasket that allows you to write code as described in the WebRTC specification without having to write prefixes or other compatibility solutions in all browsers that support WebRTC.
? Go to MDN for further study: WebRTC adapter
Core API navigator.mediaDevices.getUserMedia
When the webpage calls the camera, calling getUserMedia API,MediaDevices.getUserMedia () will prompt the user to grant permission to use the media input, which will generate a MediaStream containing the track of the requested media type. This stream can include a video track (from hardware or virtual video sources, such as cameras, video capture devices, screen sharing services, etc.), an audio track (also from hardware or virtual audio sources, such as microphones, Amax D converters, etc.), or other track types.
It returns a Promise object. If it succeeds, resolve will call back a MediaStream object. If the user refuses the permission, or the required media source is not available, promise will reject call back a PermissionDeniedError or NotFoundError. (the returned promise object may neither resolve nor reject, because the user does not have to choose to allow or deny.)
You can usually use navigator.mediaDevices to get MediaDevices, for example:
Navigator.mediaDevices.getUserMedia (constraints) .then (function (stream) {/ / use this stream}) .catch (function (err) {/ / process error})
? Go to MDN for further study: navigator.mediaDevices.getUserMedia
JSQR, a QR code parsing library
JsQR is a pure JavaScript QR code parsing library that reads the original image or camera and will locate, extract and parse any QR code in it.
If you want to use jsQR to scan the webcam stream, you need ImageData to extract from the video stream and then pass it to jsQR.
JsQR derives a method that accepts four parameters, namely, decoded image data, width, height, and optional objects to further configure the scanning behavior.
ImageData: format is [R0, G0, b0, a0, R1, G1, b1, A1,...] The rgba pixel value of the Uint8ClampedArray, an 8-bit fixed array of unsigned integers
Const code = jsQR (imageData, width, height, options); if (code) {console.log ('find the QR code!' , code);}
? Go to github to learn more: jsQR
Code implementation process
The whole scan code process is shown as follows: page initialization, first check whether the browser supports mediaDevices-related API, the browser calls off the camera, and if the call fails, the callback fails; if the call is successful, the video stream is captured, and then the scan code is identified. If no recognizable QR code is scanned, the scan continues. After the scan code is successful, the scan success pattern is drawn and the callback is successful.
The following content splits the process to achieve the corresponding functions.
Code scanning component Scaner
Page structure
Let's first take a look at the page structure, which is mainly composed of four parts:
Prompt box.
Scan the code box.
Video: show the camera to capture video streams.
Canvas: draw video frames for QR code recognition.
If the current browser cannot scan the code, please switch to other browsers
Put the QR code in the box and scan it automatically.
Start
Method: draw
Draw a line.
Picture frame (used to draw a rectangular figure after a successful scan).
/ / draw lines drawLine (begin, end) {this.canvas.beginPath (); this.canvas.moveTo (begin.x, begin.y); this.canvas.lineTo (end.x, end.y); this.canvas.lineWidth = this.lineWidth; this.canvas.strokeStyle = this.lineColor; this.canvas.stroke ();}, / / frame drawBox (location) {if (this.drawOnfound) {this.drawLine (location.topLeftCorner, location.topRightCorner) This.drawLine (location.topRightCorner, location.bottomRightCorner); this.drawLine (location.bottomRightCorner, location.bottomLeftCorner); this.drawLine (location.bottomLeftCorner, location.topLeftCorner);}}
Method: initialize
Check to see if it is supported.
Set up the camera.
Deal with success and failure.
/ / initialize setup () {/ / determines whether the browser supports the method if (navigator.mediaDevices & & navigator.mediaDevices.getUserMedia) mounted on MediaDevices.getUserMedia () {this.previousCode = null; this.parity = 0; this.active = true; this.canvas = this.$refs.canvas.getContext ("2d") / / get the camera mode. The default setting is const facingMode = this.useBackCamera? {exact: 'environment'}:' user'; / / camera video processing const handleSuccess = stream = > {if (this.$refs.video.srcObject! = = undefined) {this.$refs.video.srcObject = stream } else if (window.videoEl.mozSrcObject! = = undefined) {this.$refs.video.mozSrcObject = stream;} else if (window.URL.createObjectURL) {this.$refs.video.src = window.URL.createObjectURL (stream);} else if (window.webkitURL) {this.$refs.video.src = window.webkitURL.createObjectURL (stream);} else {this.$refs.video.src = stream } / / if you do not want the user to drag the progress bar, you can directly use the playsinline attribute: webkit-playsinline attribute this.$refs.video.playsInline = true; const playPromise = this.$refs.video.play (); playPromise.catch (() = > (this.showPlay = true)); / / periodically scan the code to identify playPromise.then (this.run) when the video starts playing;} / capture video stream navigator.mediaDevices .getUserMedia ({video: {facingMode}}) .then (handleSuccess) .catch (() = > {navigator.mediaDevices .getUserMedia ({video: true}) .then (handleSuccess) .catch (error = > {this.$emit ("getUserMedia", error);}}
Methods: periodic scanning
Run () {if (this.active) {/ / the browser invokes the code scanning method requestAnimationFrame (this.tick) before the next redrawing;}}
Method: successful callback
/ / QR Code recognition success event handling found (code) {if (this.previousCode! = = code) {this.previousCode = code;} else if (this.previousCode = code) {this.parity + = 1;} if (this.parity > 2) {this.active = this.stopOnScanned? False: true; this.parity = 0; this.$emit ("code-scanned", code);}}
Method: stop
/ / completely stop fullStop () {if (this.$refs.video & & this.$refs.video.srcObject) {/ / stop the video stream sequence track this.$refs.video.srcObject.getTracks () .forEach (t = > t.stop ());}}
Method: scan
Draw a video frame.
Scan the code to identify.
/ / periodically scan the code to identify that tick () {/ / video is in preparation and enough data has been loaded if (this.$refs.video & & this.$refs.video.readyState = this.$refs.video.HAVE_ENOUGH_DATA) {/ / start drawing video on canvas this.$refs.canvas.height = this.videoWH.height; this.$refs.canvas.width = this.videoWH.width This.canvas.drawImage (this.$refs.video, 0,0, this.$refs.canvas.width, this.$refs.canvas.height); / / getImageData () copy the pixel data of the rectangle on the canvas const imageData = this.canvas.getImageData (0,0, this.$refs.canvas.width, this.$refs.canvas.height); let code = false; try {/ / identify the QR code code = jsQR (imageData.data, imageData.width, imageData.height) } catch (e) {console.error (e);} / / if the QR code is identified, draw a rectangle if (code) {this.drawBox (code.location); / / identify successful event handling this.found (code.data);}} this.run ();}
Parent component
The parent component of Scaner mainly loads the page and displays the callback of the Scaner scan result.
Page structure
Scan QRcode
Parent component method
Import Scaner from'.. / components/Scaner';export default {name: 'Scan', components: {Scaner}, data () {return {errorMessage: ", scanned:"}}, methods: {codeScanned (code) {this.scanned = code; setTimeout (() = > {alert (`scan code parsed successfully: $[code] `) }, errorCaptured (error) {switch (error.name) {case "NotAllowedError": this.errorMessage = "Camera permission denied."; break; case "NotFoundError": this.errorMessage = "There is no connected camera."; break Case "NotSupportedError": this.errorMessage = "Seems like this page is served in non-secure context."; break; case "NotReadableError": this.errorMessage = "Couldn't access your camera. Is it already in use? "; break; case" OverconstrainedError ": this.errorMessage =" Constraints don't match any installed camera. "; break; default: this.errorMessage =" UNKNOWN ERROR: "+ error.message;} console.error (this.errorMessage); alert ('camera call failed') }}, mounted () {var str = navigator.userAgent.toLowerCase (); var ver = str.match (/ cpu iphone os (. *?) Like mac os/); / / it has been tested that systems below iOS 10.3.3 cannot successfully call camera if (ver & & ver [1]. Replace (/ _ / g, ".") < '10.3.3') {alert ('camera call failed');}}
Complete code
? Github: https://github.com/dragonir/h6-scan-qrcode
Summary of application extension
I think the following functions can be realized by calling the camera and scanning the camera through the browser. What else do you think is amazing? The functional application of the browser can be realized by scanning the code on the browser.
Link jump.
Price inquiry.
Login authentication.
File download.
Compatibility
Even if ❗ uses adapter,getUserMedia API, it is not supported in some browsers.
❗ lower version browsers (such as iOS 10.3 and below) and Android niche browsers (such as IQOO's own browser) are not compatible.
The built-in browser of ❗ QQ and Wechat cannot be called.
references
[1]。 Taking still photos with WebRTC
[2]。 Choosing cameras in JavaScript with the mediaDevices API
[3]。 How to use JavaScript to access the front and rear cameras of a device
At this point, the study on "how to use Vue to achieve browser-side code scanning function" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.