Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-webcam

Package Overview
Dependencies
Maintainers
1
Versions
66
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-webcam - npm Package Compare versions

Comparing version 2.0.1 to 3.0.0-beta.0

dist/react-webcam.d.ts

40

dist/react-webcam.js
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("prop-types"), require("react"));
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["prop-types", "react"], factory);
define(["react"], factory);
else if(typeof exports === 'object')
exports["Webcam"] = factory(require("prop-types"), require("react"));
exports["Webcam"] = factory(require("react"));
else
root["Webcam"] = factory(root["PropTypes"], root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_prop_types__, __WEBPACK_EXTERNAL_MODULE_react__) {
root["Webcam"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_react__) {
return /******/ (function(modules) { // webpackBootstrap

@@ -94,3 +94,3 @@ /******/ // The module cache

/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/react-webcam.js");
/******/ return __webpack_require__(__webpack_require__.s = "./src/react-webcam.tsx");
/******/ })

@@ -100,24 +100,14 @@ /************************************************************************/

/***/ "./src/react-webcam.js":
/*!*****************************!*\
!*** ./src/react-webcam.js ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/***/ "./src/react-webcam.tsx":
/*!******************************!*\
!*** ./src/react-webcam.tsx ***!
\******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {\n if (true) {\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(/*! react */ \"react\"), __webpack_require__(/*! prop-types */ \"prop-types\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else { var mod; }\n})(this, function (_exports, _react, _propTypes) {\n \"use strict\";\n\n Object.defineProperty(_exports, \"__esModule\", {\n value: true\n });\n _exports[\"default\"] = void 0;\n _react = _interopRequireWildcard(_react);\n _propTypes = _interopRequireDefault(_propTypes);\n\n function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj[\"default\"] = obj; return newObj; } }\n\n function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\n function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\n function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\n function _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\n function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\n function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\n function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\n function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\n function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n function _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\n function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\n function hasGetUserMedia() {\n return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);\n }\n\n var constrainStringType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string), _propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string)])\n }), _propTypes[\"default\"].shape({\n ideal: _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string)])\n })]);\n\n var constrainBooleanType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].bool\n }), _propTypes[\"default\"].shape({\n ideal: _propTypes[\"default\"].bool\n })]);\n\n var constrainLongType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].number, _propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].number,\n ideal: _propTypes[\"default\"].number,\n min: _propTypes[\"default\"].number,\n max: _propTypes[\"default\"].number\n })]);\n\n var constrainDoubleType = constrainLongType;\n\n var audioConstraintType = _propTypes[\"default\"].shape({\n deviceId: constrainStringType,\n groupId: constrainStringType,\n autoGainControl: constrainBooleanType,\n channelCount: constrainLongType,\n latency: constrainDoubleType,\n noiseSuppression: constrainBooleanType,\n sampleRate: constrainLongType,\n sampleSize: constrainLongType,\n volume: constrainDoubleType\n });\n\n var videoConstraintType = _propTypes[\"default\"].shape({\n deviceId: constrainStringType,\n groupId: constrainStringType,\n aspectRatio: constrainDoubleType,\n facingMode: constrainStringType,\n frameRate: constrainDoubleType,\n height: constrainLongType,\n width: constrainLongType\n });\n\n var propTypes = {\n audio: _propTypes[\"default\"].bool,\n onUserMedia: _propTypes[\"default\"].func,\n onUserMediaError: _propTypes[\"default\"].func,\n screenshotFormat: _propTypes[\"default\"].oneOf(['image/webp', 'image/png', 'image/jpeg']),\n screenshotQuality: _propTypes[\"default\"].number,\n minScreenshotWidth: _propTypes[\"default\"].number,\n minScreenshotHeight: _propTypes[\"default\"].number,\n audioConstraints: audioConstraintType,\n videoConstraints: videoConstraintType,\n imageSmoothing: _propTypes[\"default\"].bool\n };\n\n var Webcam =\n /*#__PURE__*/\n function (_Component) {\n _inherits(Webcam, _Component);\n\n function Webcam() {\n var _this;\n\n _classCallCheck(this, Webcam);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(Webcam).call(this));\n _this.state = {\n hasUserMedia: false\n };\n return _this;\n }\n\n _createClass(Webcam, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n if (!hasGetUserMedia()) return;\n var state = this.state;\n Webcam.mountedInstances.push(this);\n\n if (!state.hasUserMedia && !Webcam.userMediaRequested) {\n this.requestUserMedia();\n }\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(nextProps) {\n var props = this.props;\n\n if (JSON.stringify(nextProps.audioConstraints) !== JSON.stringify(props.audioConstraints) || JSON.stringify(nextProps.videoConstraints) !== JSON.stringify(props.videoConstraints)) {\n this.requestUserMedia();\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n var state = this.state;\n var index = Webcam.mountedInstances.indexOf(this);\n Webcam.mountedInstances.splice(index, 1);\n Webcam.userMediaRequested = false;\n\n if (Webcam.mountedInstances.length === 0 && state.hasUserMedia) {\n if (this.stream.getVideoTracks && this.stream.getAudioTracks) {\n this.stream.getVideoTracks().map(function (track) {\n return track.stop();\n });\n this.stream.getAudioTracks().map(function (track) {\n return track.stop();\n });\n } else {\n this.stream.stop();\n }\n\n window.URL.revokeObjectURL(state.src);\n }\n }\n }, {\n key: \"getScreenshot\",\n value: function getScreenshot() {\n var state = this.state,\n props = this.props;\n if (!state.hasUserMedia) return null;\n var canvas = this.getCanvas();\n return canvas && canvas.toDataURL(props.screenshotFormat, props.screenshotQuality);\n }\n }, {\n key: \"getCanvas\",\n value: function getCanvas() {\n var state = this.state,\n props = this.props;\n if (!state.hasUserMedia || !this.video.videoHeight) return null;\n\n if (!this.ctx) {\n var _canvas = document.createElement('canvas');\n\n var aspectRatio = this.video.videoWidth / this.video.videoHeight;\n var canvasWidth = props.minScreenshotWidth || this.video.clientWidth;\n var canvasHeight = canvasWidth / aspectRatio;\n\n if (props.minScreenshotHeight && canvasHeight < props.minScreenshotHeight) {\n canvasHeight = props.minScreenshotHeight;\n canvasWidth = canvasHeight * aspectRatio;\n }\n\n _canvas.width = canvasWidth;\n _canvas.height = canvasHeight;\n this.canvas = _canvas;\n this.ctx = _canvas.getContext('2d');\n }\n\n var ctx = this.ctx,\n canvas = this.canvas;\n ctx.imageSmoothingEnabled = props.imageSmoothing;\n ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height);\n return canvas;\n }\n }, {\n key: \"requestUserMedia\",\n value: function requestUserMedia() {\n var props = this.props;\n navigator.getUserMedia = navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;\n\n var sourceSelected = function sourceSelected(audioConstraints, videoConstraints) {\n var constraints = {\n video: typeof videoConstraints !== 'undefined' ? videoConstraints : true\n };\n\n if (props.audio) {\n constraints.audio = typeof audioConstraints !== 'undefined' ? audioConstraints : true;\n }\n\n navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {\n Webcam.mountedInstances.forEach(function (instance) {\n return instance.handleUserMedia(null, stream);\n });\n })[\"catch\"](function (e) {\n Webcam.mountedInstances.forEach(function (instance) {\n return instance.handleUserMedia(e);\n });\n });\n };\n\n if ('mediaDevices' in navigator) {\n sourceSelected(props.audioConstraints, props.videoConstraints);\n } else {\n var optionalSource = function optionalSource(id) {\n return {\n optional: [{\n sourceId: id\n }]\n };\n };\n\n var constraintToSourceId = function constraintToSourceId(constraint) {\n var _ref = constraint || {},\n deviceId = _ref.deviceId;\n\n if (typeof deviceId === 'string') {\n return deviceId;\n }\n\n if (Array.isArray(deviceId) && deviceId.length > 0) {\n return deviceId[0];\n }\n\n if (_typeof(deviceId) === 'object' && deviceId.ideal) {\n return deviceId.ideal;\n }\n\n return null;\n };\n\n MediaStreamTrack.getSources(function (sources) {\n var audioSource = null;\n var videoSource = null;\n sources.forEach(function (source) {\n if (source.kind === 'audio') {\n audioSource = source.id;\n } else if (source.kind === 'video') {\n videoSource = source.id;\n }\n });\n var audioSourceId = constraintToSourceId(props.audioConstraints);\n\n if (audioSourceId) {\n audioSource = audioSourceId;\n }\n\n var videoSourceId = constraintToSourceId(props.videoConstraints);\n\n if (videoSourceId) {\n videoSource = videoSourceId;\n }\n\n sourceSelected(optionalSource(audioSource), optionalSource(videoSource));\n });\n }\n\n Webcam.userMediaRequested = true;\n }\n }, {\n key: \"handleUserMedia\",\n value: function handleUserMedia(err, stream) {\n var props = this.props;\n\n if (err) {\n this.setState({\n hasUserMedia: false\n });\n props.onUserMediaError(err);\n return;\n }\n\n this.stream = stream;\n\n try {\n this.video.srcObject = stream;\n this.setState({\n hasUserMedia: true\n });\n } catch (error) {\n this.setState({\n hasUserMedia: true,\n src: window.URL.createObjectURL(stream)\n });\n }\n\n props.onUserMedia();\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this2 = this;\n\n var state = this.state,\n props = this.props;\n var passThroughProps = Object.entries(props).reduce(function (result, _ref2) {\n var _ref3 = _slicedToArray(_ref2, 2),\n key = _ref3[0],\n value = _ref3[1];\n\n if (Object.prototype.hasOwnProperty.call(propTypes, key)) {\n return result;\n }\n\n return _objectSpread({}, result, _defineProperty({}, key, value));\n }, {});\n return _react[\"default\"].createElement(\"video\", _extends({\n autoPlay: true,\n src: state.src,\n muted: props.audio,\n playsInline: true,\n ref: function ref(_ref4) {\n _this2.video = _ref4;\n }\n }, passThroughProps));\n }\n }]);\n\n return Webcam;\n }(_react.Component);\n\n _exports[\"default\"] = Webcam;\n Webcam.defaultProps = {\n audio: true,\n imageSmoothing: true,\n onUserMedia: function onUserMedia() {},\n onUserMediaError: function onUserMediaError() {},\n screenshotFormat: 'image/webp',\n screenshotQuality: 0.92\n };\n Webcam.propTypes = propTypes;\n Webcam.mountedInstances = [];\n Webcam.userMediaRequested = false;\n module.exports = exports.default;\n});\n\n//# sourceURL=webpack://Webcam/./src/react-webcam.js?");
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Webcam; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\nvar __rest = (undefined && undefined.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\n\nfunction hasGetUserMedia() {\n return !!((navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ||\n navigator.webkitGetUserMedia ||\n navigator.mozGetUserMedia ||\n navigator.msGetUserMedia);\n}\nclass Webcam extends react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"] {\n constructor(props) {\n super(props);\n this.ctx = null;\n this.state = {\n hasUserMedia: false\n };\n }\n componentDidMount() {\n if (!hasGetUserMedia())\n return;\n const { state } = this;\n Webcam.mountedInstances.push(this);\n if (!state.hasUserMedia && !Webcam.userMediaRequested) {\n this.requestUserMedia();\n }\n }\n componentDidUpdate(nextProps) {\n const { props } = this;\n if (JSON.stringify(nextProps.audioConstraints) !==\n JSON.stringify(props.audioConstraints) ||\n JSON.stringify(nextProps.videoConstraints) !==\n JSON.stringify(props.videoConstraints)) {\n this.requestUserMedia();\n }\n }\n componentWillUnmount() {\n const { state } = this;\n const index = Webcam.mountedInstances.indexOf(this);\n Webcam.mountedInstances.splice(index, 1);\n Webcam.userMediaRequested = false;\n if (Webcam.mountedInstances.length === 0 && state.hasUserMedia) {\n if (this.stream.getVideoTracks && this.stream.getAudioTracks) {\n this.stream.getVideoTracks().map(track => track.stop());\n this.stream.getAudioTracks().map(track => track.stop());\n }\n else {\n this.stream.stop();\n }\n if (state.src) {\n window.URL.revokeObjectURL(state.src);\n }\n }\n }\n getScreenshot() {\n const { state, props } = this;\n if (!state.hasUserMedia)\n return null;\n const canvas = this.getCanvas();\n return (canvas &&\n canvas.toDataURL(props.screenshotFormat, props.screenshotQuality));\n }\n getCanvas() {\n const { state, props } = this;\n if (!this.video) {\n return null;\n }\n if (!state.hasUserMedia || !this.video.videoHeight)\n return null;\n if (!this.ctx) {\n const canvas = document.createElement(\"canvas\");\n const aspectRatio = this.video.videoWidth / this.video.videoHeight;\n let canvasWidth = props.minScreenshotWidth || this.video.clientWidth;\n let canvasHeight = canvasWidth / aspectRatio;\n if (props.minScreenshotHeight &&\n canvasHeight < props.minScreenshotHeight) {\n canvasHeight = props.minScreenshotHeight;\n canvasWidth = canvasHeight * aspectRatio;\n }\n canvas.width = canvasWidth;\n canvas.height = canvasHeight;\n this.canvas = canvas;\n this.ctx = canvas.getContext(\"2d\");\n }\n const { ctx, canvas } = this;\n if (ctx) {\n ctx.imageSmoothingEnabled = props.imageSmoothing;\n ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height);\n }\n return canvas;\n }\n requestUserMedia() {\n const { props } = this;\n navigator.getUserMedia =\n navigator.mediaDevices.getUserMedia ||\n navigator.webkitGetUserMedia ||\n navigator.mozGetUserMedia ||\n navigator.msGetUserMedia;\n const sourceSelected = (audioConstraints, videoConstraints) => {\n const constraints = {\n video: typeof videoConstraints !== \"undefined\" ? videoConstraints : true\n };\n if (props.audio) {\n constraints.audio =\n typeof audioConstraints !== \"undefined\" ? audioConstraints : true;\n }\n navigator.mediaDevices\n .getUserMedia(constraints)\n .then(stream => {\n Webcam.mountedInstances.forEach(instance => instance.handleUserMedia(null, stream));\n })\n .catch(e => {\n Webcam.mountedInstances.forEach(instance => instance.handleUserMedia(e));\n });\n };\n if (\"mediaDevices\" in navigator) {\n sourceSelected(props.audioConstraints, props.videoConstraints);\n }\n else {\n const optionalSource = id => ({ optional: [{ sourceId: id }] });\n const constraintToSourceId = constraint => {\n const { deviceId } = constraint;\n if (typeof deviceId === \"string\") {\n return deviceId;\n }\n if (Array.isArray(deviceId) && deviceId.length > 0) {\n return deviceId[0];\n }\n if (typeof deviceId === \"object\" && deviceId.ideal) {\n return deviceId.ideal;\n }\n return null;\n };\n // @ts-ignore: deprecated api\n MediaStreamTrack.getSources(sources => {\n let audioSource = null;\n let videoSource = null;\n sources.forEach(source => {\n if (source.kind === \"audio\") {\n audioSource = source.id;\n }\n else if (source.kind === \"video\") {\n videoSource = source.id;\n }\n });\n const audioSourceId = constraintToSourceId(props.audioConstraints);\n if (audioSourceId) {\n audioSource = audioSourceId;\n }\n const videoSourceId = constraintToSourceId(props.videoConstraints);\n if (videoSourceId) {\n videoSource = videoSourceId;\n }\n sourceSelected(optionalSource(audioSource), optionalSource(videoSource));\n });\n }\n Webcam.userMediaRequested = true;\n }\n handleUserMedia(err, stream) {\n const { props } = this;\n if (err || !stream) {\n this.setState({ hasUserMedia: false });\n props.onUserMediaError(err);\n return;\n }\n this.stream = stream;\n try {\n if (this.video) {\n this.video.srcObject = stream;\n }\n this.setState({ hasUserMedia: true });\n }\n catch (error) {\n this.setState({\n hasUserMedia: true,\n src: window.URL.createObjectURL(stream)\n });\n }\n props.onUserMedia();\n }\n render() {\n const { state, props } = this;\n const { audio, onUserMedia, onUserMediaError, screenshotFormat, screenshotQuality, minScreenshotWidth, minScreenshotHeight, audioConstraints, videoConstraints, imageSmoothing } = props, rest = __rest(props, [\"audio\", \"onUserMedia\", \"onUserMediaError\", \"screenshotFormat\", \"screenshotQuality\", \"minScreenshotWidth\", \"minScreenshotHeight\", \"audioConstraints\", \"videoConstraints\", \"imageSmoothing\"]);\n return (react__WEBPACK_IMPORTED_MODULE_0__[\"createElement\"](\"video\", Object.assign({ autoPlay: true, src: state.src, muted: audio, playsInline: true, ref: ref => {\n this.video = ref;\n } }, rest)));\n }\n}\nWebcam.defaultProps = {\n audio: true,\n imageSmoothing: true,\n onUserMedia: () => { },\n onUserMediaError: () => { },\n screenshotFormat: \"image/webp\",\n screenshotQuality: 0.92\n};\nWebcam.mountedInstances = [];\nWebcam.userMediaRequested = false;\n\n\n//# sourceURL=webpack://Webcam/./src/react-webcam.tsx?");
/***/ }),
/***/ "prop-types":
/*!*********************************************************************************************************!*\
!*** external {"root":"PropTypes","commonjs2":"prop-types","commonjs":"prop-types","amd":"prop-types"} ***!
\*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_prop_types__;\n\n//# sourceURL=webpack://Webcam/external_%7B%22root%22:%22PropTypes%22,%22commonjs2%22:%22prop-types%22,%22commonjs%22:%22prop-types%22,%22amd%22:%22prop-types%22%7D?");
/***/ }),
/***/ "react":

@@ -134,3 +124,3 @@ /*!**************************************************************************************!*\

/******/ });
/******/ })["default"];
});

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("prop-types")):"function"==typeof define&&define.amd?define(["react","prop-types"],t):"object"==typeof exports?exports.Webcam=t(require("react"),require("prop-types")):e.Webcam=t(e.React,e.PropTypes)}(this,function(e,t){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){var n,o,i;o=[t,r(1),r(2)],void 0===(i="function"==typeof(n=function(r,n,o){"use strict";function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=[],n=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(n=(a=u.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){o=!0,i=e}finally{try{n||null==u.return||u.return()}finally{if(o)throw i}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(e,t){return!t||"object"!==s(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0,n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){var n=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,r):{};n.get||n.set?Object.defineProperty(t,r,n):t[r]=e[r]}return t.default=e,t}(n);var p,h=(p=o,o=p&&p.__esModule?p:{default:p}).default.oneOfType([o.default.string,o.default.arrayOf(o.default.string),o.default.shape({exact:o.default.oneOfType([o.default.string,o.default.arrayOf(o.default.string)])}),o.default.shape({ideal:o.default.oneOfType([o.default.string,o.default.arrayOf(o.default.string)])})]),v=o.default.oneOfType([o.default.shape({exact:o.default.bool}),o.default.shape({ideal:o.default.bool})]),y=o.default.oneOfType([o.default.number,o.default.shape({exact:o.default.number,ideal:o.default.number,min:o.default.number,max:o.default.number})]),m=y,g=o.default.shape({deviceId:h,groupId:h,autoGainControl:v,channelCount:y,latency:m,noiseSuppression:v,sampleRate:y,sampleSize:y,volume:m}),b=o.default.shape({deviceId:h,groupId:h,aspectRatio:m,facingMode:h,frameRate:m,height:y,width:y}),O={audio:o.default.bool,onUserMedia:o.default.func,onUserMediaError:o.default.func,screenshotFormat:o.default.oneOf(["image/webp","image/png","image/jpeg"]),screenshotQuality:o.default.number,minScreenshotWidth:o.default.number,minScreenshotHeight:o.default.number,audioConstraints:g,videoConstraints:b,imageSmoothing:o.default.bool},M=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=d(this,f(t).call(this))).state={hasUserMedia:!1},e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&l(e,t)}(t,e),r=t,(o=[{key:"componentDidMount",value:function(){if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia){var e=this.state;t.mountedInstances.push(this),e.hasUserMedia||t.userMediaRequested||this.requestUserMedia()}}},{key:"componentDidUpdate",value:function(e){var t=this.props;JSON.stringify(e.audioConstraints)===JSON.stringify(t.audioConstraints)&&JSON.stringify(e.videoConstraints)===JSON.stringify(t.videoConstraints)||this.requestUserMedia()}},{key:"componentWillUnmount",value:function(){var e=this.state,r=t.mountedInstances.indexOf(this);t.mountedInstances.splice(r,1),t.userMediaRequested=!1,0===t.mountedInstances.length&&e.hasUserMedia&&(this.stream.getVideoTracks&&this.stream.getAudioTracks?(this.stream.getVideoTracks().map(function(e){return e.stop()}),this.stream.getAudioTracks().map(function(e){return e.stop()})):this.stream.stop(),window.URL.revokeObjectURL(e.src))}},{key:"getScreenshot",value:function(){var e=this.state,t=this.props;if(!e.hasUserMedia)return null;var r=this.getCanvas();return r&&r.toDataURL(t.screenshotFormat,t.screenshotQuality)}},{key:"getCanvas",value:function(){var e=this.state,t=this.props;if(!e.hasUserMedia||!this.video.videoHeight)return null;if(!this.ctx){var r=document.createElement("canvas"),n=this.video.videoWidth/this.video.videoHeight,o=t.minScreenshotWidth||this.video.clientWidth,i=o/n;t.minScreenshotHeight&&i<t.minScreenshotHeight&&(i=t.minScreenshotHeight,o=i*n),r.width=o,r.height=i,this.canvas=r,this.ctx=r.getContext("2d")}var a=this.ctx,u=this.canvas;return a.imageSmoothingEnabled=t.imageSmoothing,a.drawImage(this.video,0,0,u.width,u.height),u}},{key:"requestUserMedia",value:function(){var e=this.props;navigator.getUserMedia=navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var r=function(r,n){var o={video:void 0===n||n};e.audio&&(o.audio=void 0===r||r),navigator.mediaDevices.getUserMedia(o).then(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(null,e)})}).catch(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(e)})})};if("mediaDevices"in navigator)r(e.audioConstraints,e.videoConstraints);else{var n=function(e){return{optional:[{sourceId:e}]}},o=function(e){var t=e||{},r=t.deviceId;return"string"==typeof r?r:Array.isArray(r)&&r.length>0?r[0]:"object"===s(r)&&r.ideal?r.ideal:null};MediaStreamTrack.getSources(function(t){var i=null,a=null;t.forEach(function(e){"audio"===e.kind?i=e.id:"video"===e.kind&&(a=e.id)});var u=o(e.audioConstraints);u&&(i=u);var s=o(e.videoConstraints);s&&(a=s),r(n(i),n(a))})}t.userMediaRequested=!0}},{key:"handleUserMedia",value:function(e,t){var r=this.props;if(e)return this.setState({hasUserMedia:!1}),void r.onUserMediaError(e);this.stream=t;try{this.video.srcObject=t,this.setState({hasUserMedia:!0})}catch(e){this.setState({hasUserMedia:!0,src:window.URL.createObjectURL(t)})}r.onUserMedia()}},{key:"render",value:function(){var e=this,t=this.state,r=this.props,o=Object.entries(r).reduce(function(e,t){var r=u(t,2),n=r[0],o=r[1];return Object.prototype.hasOwnProperty.call(O,n)?e:function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){a(e,t,r[t])})}return e}({},e,a({},n,o))},{});return n.default.createElement("video",i({autoPlay:!0,src:t.src,muted:r.audio,playsInline:!0,ref:function(t){e.video=t}},o))}}])&&c(r.prototype,o),p&&c(r,p),t;var r,o,p}(n.Component);r.default=M,M.defaultProps={audio:!0,imageSmoothing:!0,onUserMedia:function(){},onUserMediaError:function(){},screenshotFormat:"image/webp",screenshotQuality:.92},M.propTypes=O,M.mountedInstances=[],M.userMediaRequested=!1,e.exports=t.default})?n.apply(t,o):n)||(e.exports=i)},function(t,r){t.exports=e},function(e,r){e.exports=t}])});
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.Webcam=t(require("react")):e.Webcam=t(e.React)}(this,function(e){return function(e){var t={};function i(s){if(t[s])return t[s].exports;var n=t[s]={i:s,l:!1,exports:{}};return e[s].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=e,i.c=t,i.d=function(e,t,s){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(s,n,function(t){return e[t]}.bind(null,n));return s},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=1)}([function(t,i){t.exports=e},function(e,t,i){"use strict";i.r(t),i.d(t,"default",function(){return r});var s=i(0),n=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(i[s[n]]=e[s[n]])}return i};class r extends s.Component{constructor(e){super(e),this.ctx=null,this.state={hasUserMedia:!1}}componentDidMount(){if(!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia))return;const{state:e}=this;r.mountedInstances.push(this),e.hasUserMedia||r.userMediaRequested||this.requestUserMedia()}componentDidUpdate(e){const{props:t}=this;JSON.stringify(e.audioConstraints)===JSON.stringify(t.audioConstraints)&&JSON.stringify(e.videoConstraints)===JSON.stringify(t.videoConstraints)||this.requestUserMedia()}componentWillUnmount(){const{state:e}=this,t=r.mountedInstances.indexOf(this);r.mountedInstances.splice(t,1),r.userMediaRequested=!1,0===r.mountedInstances.length&&e.hasUserMedia&&(this.stream.getVideoTracks&&this.stream.getAudioTracks?(this.stream.getVideoTracks().map(e=>e.stop()),this.stream.getAudioTracks().map(e=>e.stop())):this.stream.stop(),e.src&&window.URL.revokeObjectURL(e.src))}getScreenshot(){const{state:e,props:t}=this;if(!e.hasUserMedia)return null;const i=this.getCanvas();return i&&i.toDataURL(t.screenshotFormat,t.screenshotQuality)}getCanvas(){const{state:e,props:t}=this;if(!this.video)return null;if(!e.hasUserMedia||!this.video.videoHeight)return null;if(!this.ctx){const e=document.createElement("canvas"),i=this.video.videoWidth/this.video.videoHeight;let s=t.minScreenshotWidth||this.video.clientWidth,n=s/i;t.minScreenshotHeight&&n<t.minScreenshotHeight&&(s=(n=t.minScreenshotHeight)*i),e.width=s,e.height=n,this.canvas=e,this.ctx=e.getContext("2d")}const{ctx:i,canvas:s}=this;return i&&(i.imageSmoothingEnabled=t.imageSmoothing,i.drawImage(this.video,0,0,s.width,s.height)),s}requestUserMedia(){const{props:e}=this;navigator.getUserMedia=navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;const t=(t,i)=>{const s={video:void 0===i||i};e.audio&&(s.audio=void 0===t||t),navigator.mediaDevices.getUserMedia(s).then(e=>{r.mountedInstances.forEach(t=>t.handleUserMedia(null,e))}).catch(e=>{r.mountedInstances.forEach(t=>t.handleUserMedia(e))})};if("mediaDevices"in navigator)t(e.audioConstraints,e.videoConstraints);else{const i=e=>({optional:[{sourceId:e}]}),s=e=>{const{deviceId:t}=e;return"string"==typeof t?t:Array.isArray(t)&&t.length>0?t[0]:"object"==typeof t&&t.ideal?t.ideal:null};MediaStreamTrack.getSources(n=>{let r=null,o=null;n.forEach(e=>{"audio"===e.kind?r=e.id:"video"===e.kind&&(o=e.id)});const a=s(e.audioConstraints);a&&(r=a);const d=s(e.videoConstraints);d&&(o=d),t(i(r),i(o))})}r.userMediaRequested=!0}handleUserMedia(e,t){const{props:i}=this;if(e||!t)return this.setState({hasUserMedia:!1}),void i.onUserMediaError(e);this.stream=t;try{this.video&&(this.video.srcObject=t),this.setState({hasUserMedia:!0})}catch(e){this.setState({hasUserMedia:!0,src:window.URL.createObjectURL(t)})}i.onUserMedia()}render(){const{state:e,props:t}=this,{audio:i,onUserMedia:r,onUserMediaError:o,screenshotFormat:a,screenshotQuality:d,minScreenshotWidth:c,minScreenshotHeight:u,audioConstraints:h,videoConstraints:l,imageSmoothing:m}=t,f=n(t,["audio","onUserMedia","onUserMediaError","screenshotFormat","screenshotQuality","minScreenshotWidth","minScreenshotHeight","audioConstraints","videoConstraints","imageSmoothing"]);return s.createElement("video",Object.assign({autoPlay:!0,src:e.src,muted:i,playsInline:!0,ref:e=>{this.video=e}},f))}}r.defaultProps={audio:!0,imageSmoothing:!0,onUserMedia:()=>{},onUserMediaError:()=>{},screenshotFormat:"image/webp",screenshotQuality:.92},r.mountedInstances=[],r.userMediaRequested=!1}]).default});

@@ -167,3 +167,5 @@ // For a detailed explanation regarding each configuration property, visit:

// A map from regular expressions to paths to transformers
// transform: null,
transform: {
"^.+\\.tsx?$": "ts-jest"
}

@@ -170,0 +172,0 @@ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation

{
"name": "react-webcam",
"version": "2.0.1",
"version": "3.0.0-beta.0",
"description": "React webcam component",
"main": "dist/react-webcam.js",
"types": "dist/react-webcam.d.ts",
"scripts": {
"prepublish": "npm run build:production",
"build": "NODE_ENV=development webpack-cli src/react-webcam.js",
"build:production": "npm run build && NODE_ENV=production webpack-cli src/react-webcam.js",
"lint": "eslint src",
"build": "NODE_ENV=development webpack-cli",
"build:production": "npm run build && NODE_ENV=production webpack-cli",
"lint": "eslint src/react-webcam.tsx",
"test": "jest"

@@ -33,15 +34,11 @@ },

"devDependencies": {
"@babel/core": "^7.4.5",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.6",
"babel-plugin-add-module-exports": "^1.0.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-jest": "^22.6.4",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.13.0",
"@types/jest": "^24.0.18",
"@types/react": "^16.9.2",
"@types/react-dom": "^16.9.0",
"@types/react-test-renderer": "^16.9.0",
"@typescript-eslint/eslint-plugin": "^2.1.0",
"@typescript-eslint/parser": "^2.1.0",
"awesome-typescript-loader": "^5.2.1",
"eslint": "^6.3.0",
"eslint-plugin-react": "^7.14.3",
"jest": "^24.8.0",

@@ -51,8 +48,8 @@ "react": "^16.3.1",

"react-test-renderer": "^16.8.6",
"source-map-loader": "^0.2.4",
"ts-jest": "^24.0.2",
"typescript": "^3.6.2",
"webpack": "^4.32.2",
"webpack-cli": "^3.3.2"
},
"dependencies": {
"prop-types": "^15.7.2"
}
}

@@ -29,7 +29,3 @@ # react-webcam

class Component extends React.Component {
render() {
return <Webcam />;
}
}
const WebcamComponent = () => <Webcam />;
```

@@ -58,34 +54,35 @@

[CodePen demo](https://codepen.io/mozmorris/pen/wvwqm)
```javascript
class WebcamCapture extends React.Component {
setRef = webcam => {
this.webcam = webcam;
};
const videoConstraints = {
width: 1280,
height: 720,
facingMode: "user"
};
capture = () => {
const imageSrc = this.webcam.getScreenshot();
};
const WebcamCapture = () => {
const webcamRef = React.useRef(null);
render() {
const videoConstraints = {
width: 1280,
height: 720,
facingMode: "user"
};
const capture = React.useCallback(
() => {
const imageSrc = webcamRef.current.getScreenshot();
},
[webcamRef]
);
return (
<div>
<Webcam
audio={false}
height={720}
ref={this.setRef}
screenshotFormat="image/jpeg"
width={1280}
videoConstraints={videoConstraints}
/>
<button onClick={this.capture}>Capture photo</button>
</div>
);
}
}
return (
<>
<Webcam
audio={false}
height={720}
ref={webcamRef}
screenshotFormat="image/jpeg"
width={1280}
videoConstraints={videoConstraints}
/>
<button onClick={capture}>Capture photo</button>
</>
);
};
```

@@ -92,0 +89,0 @@

@@ -16,16 +16,14 @@ module.exports = {

amd: "react-dom"
},
"prop-types": {
root: "PropTypes",
commonjs2: "prop-types",
commonjs: "prop-types",
amd: "prop-types"
}
}
],
entry: "./src/react-webcam.tsx",
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
module: {
rules: [
{
test: /\.js$/,
use: "babel-loader"
test: /\.(t|j)sx?$/,
use: "awesome-typescript-loader"
}

@@ -41,4 +39,5 @@ ]

: "react-webcam.js",
globalObject: "this"
globalObject: "this",
libraryExport: "default"
}
};

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc