UNPKG

@e-group/material-lab

Version:

EGroup Team Lab - Incubator for EGroup Team experimental React components.

77 lines (66 loc) 2.49 kB
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import { useCallback } from 'react'; const isBrowser = typeof document !== 'undefined'; export default function useGetVideoSnapshot(ref, options = {}) { const mirrored = options.mirrored; const getVideoSnapshot = useCallback( /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(type, quality) { var canvas, ctx; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (isBrowser) { _context.next = 2; break; } return _context.abrupt("return", Promise.reject(new Error('Not browser environment.'))); case 2: canvas = document.createElement('canvas'); if (!(!ref || !ref.current)) { _context.next = 5; break; } return _context.abrupt("return", new Promise(resolve => resolve(undefined))); case 5: canvas.width = ref.current.videoWidth; canvas.height = ref.current.videoHeight; ctx = canvas.getContext('2d'); // fixed ctx maybe null issue // https://github.com/microsoft/TypeScript/issues/19229 if (ctx) { _context.next = 10; break; } throw new Error("2d context not supported or canvas already initialized"); case 10: if (mirrored) { ctx.scale(-1, 1); ctx.drawImage(ref.current, 0, 0, canvas.width * -1, canvas.height); } else { ctx.drawImage(ref.current, 0, 0); } return _context.abrupt("return", new Promise((resolve, reject) => { try { canvas.toBlob(blob => { resolve({ canvas, ctx, blob }); }, type, quality); } catch (error) { reject(error); } })); case 12: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(), [ref, mirrored]); return [getVideoSnapshot]; }