【问题标题】:Not closing camera in zxing在 zxing 中不关闭摄像头
【发布时间】:2020-05-22 11:05:37
【问题描述】:

在 Zxing 库中,我想在用户单击取消时关闭摄像头。所以我使用了一个按钮并向它添加了 onclick 事件。它正在调用 resetReader 方法。我在获取条形码值后或在取消按钮 onclick 事件中调用了此方法。如果它正在获取条形码值,则此 resetReader 方法可以正常工作。如果我们取消,相机不会停止。我错过了什么吗?

const codeReader = new BrowserMultiFormatReader(hints);

const resetReader = () => {
    codeReader.reset();
    codeReader.stopContinuousDecode();
  };

【问题讨论】:

  • 您好,我也在调查这个问题。你找到解决办法了吗?

标签: zxing zxing-js


【解决方案1】:

对于那些还没有弄清楚的人?我找到了解决这个问题的方法。 Harendrra 的解决方案对我不起作用,但这个解决方案与 usestate 结合使用。对于我的项目,代码使用 Bootstrap。因此,当我单击一个按钮时,会出现模态。相机加载。当我单击关闭按钮时,相机会消失。希望这是每个人的解决方案,享受;-)

export default function Example(props) {
  // codeReader
  const [codeReader, setReader] = useState(new BrowserMultiFormatReader());
  const [videoInputDevices, setVideoInputDevices] = useState([]);
  const [selectedVideoDevice, selectVideoDevice] = useState('');

  useEffect(() => {
    (async () => {
        const videoInputDeviceList = await codeReader.listVideoInputDevices();
        setVideoInputDevices(videoInputDeviceList);
        if (videoInputDeviceList.length > 0 && selectedVideoDevice == null) {
            selectVideoDevice(videoInputDeviceList[0].deviceId);
        }
    })();
  }, [codeReader, selectedVideoDevice]);

  const handleShow = () => {
    setBrand('');
    // Open modal.
    setShow(true);

    codeReader.decodeFromVideoDevice(selectedVideoDevice, 'videoElement', (res) => {
        setCanClose(true);
        if (res) {
            const rawText = res.getText();
            axios
                .get(`https://world.openfoodfacts.org/api/v0/product/${rawText}.json`)
                .then((result) => {
                    // set data
                    setBrand(result.data.product.brands);
                    // close modal
                    setShow(false);
                    // codeReader reset
                    codeReader.reset();
                })
                .catch((err) => console.log('error', err));
          }
      });
  };

  const handleClose = () => {
    // codeReader reset.
    setReader(codeReader.reset());
    // Close modal
    setShow(false);
    // Set new codeReader.
    // The solution for the error messages after the codeReader reset.
    // This will build the codeReader for the next time.
    setReader(new BrowserMultiFormatReader(hints));
  };

  return (
    <Fragment>
      <div className='py-2'>
        <div>Brand: {brand}</div>
        <Button variant='primary' onClick={handleShow}>
          Launch static backdrop modal
        </Button>

        <Modal show={show} onHide={handleClose} backdrop='static' keyboard={false} centered id='scanProductModal'>
          <Modal.Body>
            <div
              onChange={(event) => {
                const deviceId = event.target.value;
                selectVideoDevice(deviceId);
              }}
            >
              <div className='button-group-top'>
                <select className='form-select form-select-sm' aria-label='Default select example'>
                  {videoInputDevices &&                                          
                    videoInputDevices.map((inputDevice, index) => {
                      return (
                        <option value={inputDevice.deviceId} key={index}>
                          {inputDevice.label || inputDevice.deviceId}
                        </option>
                      );
                  })}
                </select>
              </div>
             
              <video id='videoElement' width='600' height='400' />
              <Button className='btn btn-danger' onClick={handleClose}>
                Close
              </Button>
            </div>
          </Modal.Body>
        </Modal>
      </Fragment>
    );
  }

【讨论】:

    【解决方案2】:

    是的,我解决了。您必须在类的顶部创建 codeReader 对象。试试这个代码。

    import "../App.css";
    import { BrowserBarcodeReader } from "@zxing/library";
    
    class Barcode extends React.Component {
       codeReader = new BrowserBarcodeReader();
      constructor(props) {
        super(props);
        this.state = { reader: {}, selectedDevice: "" };
        this.startButton = this.startButton.bind(this);
        this.resetButton = this.resetButton.bind(this);
        this.getBarcode = this.getBarcode.bind(this);
      }
      componentDidMount() {
        this.getBarcode();
      }
    
      startButton() {
        console.log("start", this.codeReader);
        this.codeReader
          .decodeOnceFromVideoDevice(this.state.selectedDevice, "video")
          .then(result => {
            document.getElementById("result").textContent = result.text;
          })
          .catch(err => {
            console.error(err.toString());
            document.getElementById("result").textContent = err;
          });
        console.log(
          `Started continous decode from camera with id ${this.state.selectedDevice}`
        );
      }
    
      resetButton() {
        this.codeReader && this.codeReader.reset();
        document.getElementById("result").textContent = "";
      }
    
      getBarcode() {
        let selectedDeviceId;
       
        return this.codeReader.getVideoInputDevices().then(videoInputDevices => {
            const sourceSelect = document.getElementById("sourceSelect");
            selectedDeviceId = videoInputDevices[0].deviceId;
            if (videoInputDevices.length > 1) {
              videoInputDevices.forEach(element => {
                const sourceOption = document.createElement("option");
                sourceOption.text = element.label;
                sourceOption.value = element.deviceId;
                sourceSelect.appendChild(sourceOption);
              });
    
              sourceSelect.onchange = () => {
                selectedDeviceId = sourceSelect.value;
              };
    
              const sourceSelectPanel = document.getElementById(
                "sourceSelectPanel"
              );
              sourceSelectPanel.style.display = "block";
            }
            this.setState({
              selectedDevice: selectedDeviceId
            });
          })
          .catch(err => {
            alert(err);
          });
      }
    
      render() {
        return (
          <div>
            <h2>Barcode</h2>
            {Object.keys(this.codeReader).length > 0 && (
              <div>
                <div>
                  <button
                    className="button"
                    id="startButton"
                    onClick={this.startButton}
                  >
                    Start
                  </button>
                  <button
                    className="button"
                    id="resetButton"
                    onClick={this.resetButton}
                  >
                    Reset
                  </button>
                </div>
    
                <div>
                  <video
                    id="video"
                    width="600"
                    height="400"
                    style={{ border: "1px solid gray" }}
                  ></video>
                </div>
    
                <label>Result:</label>
                <pre>
                  <code id="result"></code>
                </pre>
              </div>
            )}
          </div>
        );
      }
    }
    
    export default Barcode; ```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多