This is the first time for XDM to write an article. Please point out the shortcomings and modify them.

Install the zxing library

npm install @zxing/library --save

Vue introduced in

import { BrowserMultiFormatReader } from "@zxing/library"
Copy the code

prompt

This code needs to be in an HTTPS environment to call the camera

Code implementation JS code

export default defineComponent({
  setup(props) {
    let codeReader = reactive(new BrowserMultiFormatReader());
    onMounted(() = > {
      openScan();
    });
    let openScan = async () => {
      codeReader
        .listVideoInputDevices()
        .then((videoInputDevices) = > {
          console.log("videoInputDevices", videoInputDevices, "Camera equipment");

          // Get the first camera device ID by default
          let firstDeviceId = videoInputDevices[0].deviceId;  // Select the camera based on the ID

          decodeFromInputVideoFunc(firstDeviceId);
          // navigator.getUserMedia(
          // { video: { deviceId: firstDeviceId } },
          //   () => {
          // console.log(document.cookie);
          // decodeFromInputVideoFunc(firstDeviceId);
          / /},
          //   () => {
          // Toast(" Please close the link and re-enter ");
          // router.back();
          / /}
          // );
        })
        .catch((err) = > {});
    };

    let decodeFromInputVideoFunc = (firstDeviceId: any) = > {
      codeReader.decodeFromInputVideoDeviceContinuously(
        null.// If firstDeviceId is null, the context-oriented camera is selected by default
        "video".(result: any, err) = > {
          if (result) {
            console.log(result, "Scan results");
          }
          if(err && ! err) {console.error(err); }}); }; onBeforeUnmount(() = > {
      codeReader.reset();
    });
    return{}; }});Copy the code
listVideoInputDevices  Get an array of camera devices and select the camera to use based on the id of the camera

decodeFromInputVideoDeviceContinuously() // The first parameter is the id of the camera from the previous array. Select the camera scan based on the passed camera ID. If the ID is null, the environment facing camera is used by default
Copy the code

The HTML code

<div class="QrCode">
    <video ref="video" height="100%" width="100%" id="video" autoplay></video>
  </div>
  <div class="Qr_scanner">
    <div class="box">
      <div class="line_row">
        <div class="line"></div>
      </div>
      <div class="angle"></div>
    </div>
  </div>
Copy the code

The source address

Github source address

Zxing library github address

CSS animation Baidu to find an old brother animation