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
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();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With