Antdesignpro realizes calling USB camera to take pictures and upload demo

1. First upload the renderings:

2. Before using my demo, first determine your environment. There are only two environments that can be accessed: 1. localhost; 2. https

3. Upload the code! ! ! ! !

import type { ProFormInstance } from '@ant-design/pro-form';
import ProCard from "@ant-design/pro-card";
import {Button, Col, message, Row} from 'antd';
import {
  ProForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
} from '@ant-design/pro-form';
import React, {useRef, useState} from 'react';
import moment from "moment";
// import "./components/video.js"


// const [State, setState] = useState();

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const formRef = useRef<ProFormInstance>();
  let video_ref: any = useRef();
  let mediaStream:any = null;

  // Clear the preview canvas
  const closeCanas = () => {
    let canvas = document.getElementById("canvas");
    // @ts-ignore
    let ctx = canvas.getContext('2d');
    ctx.clearRect(0, 20, 400, 320)
  }

  // close the camera
  const onCloseDevice = () => {
    //closure
    if(mediaStream) {
      if (mediaStream.active == true) {
        let track = mediaStream.getTracks()[0];
        track.stop();
      }
    }
  }
  //Get the video camera area
  const getMedia = async ()=>{
    closeCanas()
    let video = video_ref.current;
    let constraints = {
      video: {width: 480, height: 320},
      audio: false
    };
    try {
      mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
      video.srcObject = mediaStream;
      video.play();
    } catch (e) {
      // @ts-ignore
      // message.error(e);
      console.log(e)
    }
  }
  // getMedia()
  const takePhoto = ()=>{
    if(mediaStream){
      if(mediaStream.active == true){
        //Get the Canvas object
        let canvas = document.getElementById("canvas");
        // @ts-ignore
        let ctx = canvas.getContext('2d');
        ctx.drawImage(video_ref.current, 0, 20, 400, 320);
        toBase64()
        // onCloseDevice()
      }
      else{
        message.error("The device has not been opened, please open the device first!")
      }
    }
    else{
      message.error("The device has not been opened, please open the device first!")
    }
  }
  let base64Data = null;
  const toBase64 = () => {
    //Get the Canvas object
    let canvas = document.getElementById("canvas");
    //Get the photo data from the canvas
    // @ts-ignore
    var imgData = canvas.toDataURL();
    //Convert image to Base64
    base64Data = imgData.substr(22);
    console.log("base64Data:"+base64Data);
    message.success("Uploaded successfully!")
  }

  return (
    <ProCard>
      <StepsForm<{
        name: string;
      }>
        formRef={formRef}
        onFinish={async (values) => {
          await waitTime(3000);
          if(!base64Data){
            message.error('Please upload a picture')
            return;
          }
          values.aa = base64Data
          console.log(1111,values);

          message.success('submitted successfully');
          onCloseDevice()
        }}
        formProps={
  
  {
          validateMessages: {
            required: 'This item is required',
          },
        }}
      >
        <StepsForm.StepForm<{
          name: string;
        }>
          name="base"
          title="Start check-in hotel"
          stepProps={
  
  {
            description: 'Please choose a suitable room and fill in the certificate information',
          }}
          onFinish={async () => {
            console.log(formRef.current?.getFieldsValue());
            return true;
          }}
        >


        </StepsForm.StepForm>
        <StepsForm.StepForm<{
          checkbox: string;
        }>
          name="checkbox"
          title="Live photo"
          stepProps={
  
  {
            description: 'Please upload passenger photos',
          }}
          onFinish={async () => {
            console.log(formRef.current?.getFieldsValue());
            return true;
          }}
        >
          <div>
            <div style={
  
  {backgroundColor: "#FFF", padding: '20px'}}>
              <Row>
                <Col span={12} key={1}>
                  <h3>Live screen:</h3>
                  <video ref={video_ref} id="video" width="400" height="320" controls>
                  </video>
                  {/*<Row style={
  
  {marginTop: "36px"}}>*/}
                  {/*  <Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={getMedia}>Open device</Button>*/}
                  {/*</Row>*/}
                  <Row style={
  
  {marginTop: "36px"}}>
                    <Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={getMedia}>Open device</Button>
                    <Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={takePhoto}>take photo and upload</Button>
                    {/*<Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={toBase64}>OK to upload</Button>*/}
                    {/*<Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={onCloseDevice}>Close device</Button>*/}
                    {/*<Button type="primary" style={
  
  {marginLeft: '20px'}} onClick={closeCanas}>Clear preview</Button>*/}
                  </Row>
                </Col>
                <Col>
                  <div>
                    <h3>Preview:</h3>
                    <canvas id="canvas" width="400" height="320" ></canvas>
                  </div>
                </Col>
              </Row>
            </div>
          </div>
          {/*<ProFormUploadButton width="sm" name="LK_ZP" label="Passenger Photo" max={1} rules={[{ required: true, message: "This is a required field" }]}/>* /}
        </StepsForm.StepForm>
        <StepsForm.StepForm
          name="time"
          title="Submit check-in"
          stepProps={
  
  {
            description: 'Fill in other information here, such as license plate number, etc',
          }}
        >
        </StepsForm.StepForm>
      </StepsForm>
    </ProCard>
  );
};

Guess you like

Origin blog.csdn.net/lystest/article/details/125402255