Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take a picture in React web application (not native)

I need to have ability to take a picture with desktop camera or mobile phone camera from my web application localhost:3000/user-camera route component. And, please dont write about any native solutions because I'm not working on mobile app.

I have try with react-camera and react-webcam package but nothing works. https://www.npmjs.com/package/react-webcam

Import React from 'react'
Import Webcam from 'react-webcam'

const videoConstraints = {
  width: 1280,
  height: 720,
  facingMode: "user"
};

const WebcamCapture = () => {
  const webcamRef = React.useRef(null);

  const capture = React.useCallback(
    () => {
      const imageSrc = webcamRef.current.getScreenshot();
    },
    [webcamRef]
  );

  return (
    <>
      <Webcam
        audio={false}
        height={720}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        width={1280}
        videoConstraints={videoConstraints}
      />
      <button onClick={capture}>Capture photo</button>
    </>
  );
};

So, is there a way to do this by using javascript maybe using navigator, or is there a npm package that works with react. Does anyone have experience with this?

Thanks

like image 911
Saban Avatar asked Nov 11 '19 18:11

Saban


Video Answer


1 Answers

Try this simple module I created on the fly just to test this interesting feature:

const camera = function () {
let width = 0;
let height = 0;

const createObjects = function () {


    const video = document.createElement('video');
    video.id = 'video';
    video.width = width;
    video.width = height;
    video.autoplay = true;
    document.body.appendChild(video);

    const canvas = document.createElement('canvas');
    canvas.id = 'canvas';
    canvas.width = width;
    canvas.width = height;
    document.body.appendChild(canvas);
}


return {
    video: null,
    context: null,
    canvas: null,

    startCamera: function (w = 680, h = 480) {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            width = w;
            height = h;

            createObjects();

            this.video = document.getElementById('video');
            this.canvas = document.getElementById('canvas');
            this.context = this.canvas.getContext('2d');


            (function (video) {
                navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) {
                    video.srcObject = stream;
                    video.play();
                });
            })(this.video)

        }
    },


    takeSnapshot: function () {
        this.context.drawImage(this.video, 0, 0, width, height);
    }

}
}();

export default camera;

To use this module first import it as regular es6 module

import camera from './camera.js'

Then call:

camera.startCamera();
camera.takeSnapshot();
like image 132
Dalibor Avatar answered Oct 19 '22 03:10

Dalibor