如何从视频中读取二维码,而无需在 zxing 的 js 库中传递 deviceId

问题描述 投票:0回答:1

decodeFromInputVideoDevice
函数仅在我们将 deviceID 传递给它时才起作用。 它有任何其他功能可以直接传递相机流,而不传递 deviceId

我无法找到文档中的特定用例

javascript web qr-code zxing zxing-js
1个回答
0
投票

要使用 ZXing 的 JavaScript 库从视频流中读取 QR 码,您可以使用“getUserMedia”API 访问摄像头并创建视频流,然后使用“canvas”元素从视频流中捕获图像。

// Create a video element and add it to the page
var video = document.createElement('video');
document.body.appendChild(video);

// Get the user media
navigator.mediaDevices.getUserMedia({ video: true })
  .then(function(stream) {
    // Set the video source to the stream
    video.srcObject = stream;
    video.play();

    // Create a canvas element to capture images from the video stream
    var canvas = document.createElement('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    var ctx = canvas.getContext('2d');

    // Start decoding QR codes
    const codeReader = new ZXing.BrowserQRCodeReader();
    codeReader.decodeFromVideoDevice(undefined, 'video', (result, error) => {
      if (result) {
        // Do something with the decoded result
        console.log(result.text);
      }
      if (error) {
        console.error(error);
      }
    });
  })
  .catch(function(err) {
    console.error(err);
  });
© www.soinside.com 2019 - 2024. All rights reserved.