webcam.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. // WebcamJS v1.0.22
  2. // Webcam library for capturing JPEG/PNG images in JavaScript
  3. // Attempts getUserMedia, falls back to Flash
  4. // Author: Joseph Huckaby: http://github.com/jhuckaby
  5. // Based on JPEGCam: http://code.google.com/p/jpegcam/
  6. // Copyright (c) 2012 - 2017 Joseph Huckaby
  7. // Licensed under the MIT License
  8. (function(window) {
  9. var _userMedia;
  10. // declare error types
  11. // inheritance pattern here:
  12. // https://stackoverflow.com/questions/783818/how-do-i-create-a-custom-error-in-javascript
  13. function FlashError() {
  14. var temp = Error.apply(this, arguments);
  15. temp.name = this.name = "FlashError";
  16. this.stack = temp.stack;
  17. this.message = temp.message;
  18. }
  19. function WebcamError() {
  20. var temp = Error.apply(this, arguments);
  21. temp.name = this.name = "WebcamError";
  22. this.stack = temp.stack;
  23. this.message = temp.message;
  24. }
  25. IntermediateInheritor = function() {};
  26. IntermediateInheritor.prototype = Error.prototype;
  27. FlashError.prototype = new IntermediateInheritor();
  28. WebcamError.prototype = new IntermediateInheritor();
  29. var Webcam = {
  30. version: '1.0.22',
  31. // globals
  32. protocol: location.protocol.match(/https/i) ? 'https' : 'http',
  33. loaded: false, // true when webcam movie finishes loading
  34. live: false, // true when webcam is initialized and ready to snap
  35. userMedia: true, // true when getUserMedia is supported natively
  36. iOS: /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream,
  37. params: {
  38. width: 0,
  39. height: 0,
  40. dest_width: 0, // size of captured image
  41. dest_height: 0, // these default to width/height
  42. image_format: 'jpeg', // image format (may be jpeg or png)
  43. jpeg_quality: 90, // jpeg image quality from 0 (worst) to 100 (best)
  44. enable_flash: true, // enable flash fallback,
  45. force_flash: false, // force flash mode,
  46. flip_horiz: false, // flip image horiz (mirror mode)
  47. fps: 30, // camera frames per second
  48. upload_name: 'webcam', // name of file in upload post data
  49. constraints: null, // custom user media constraints,
  50. swfURL: '', // URI to webcam.swf movie (defaults to the js location)
  51. flashNotDetectedText: 'ERROR: No Adobe Flash Player detected. Webcam.js relies on Flash for browsers that do not support getUserMedia (like yours).',
  52. noInterfaceFoundText: 'No supported webcam interface found.',
  53. unfreeze_snap: true, // Whether to unfreeze the camera after snap (defaults to true)
  54. iosPlaceholderText: 'Click here to open camera.',
  55. user_callback: null, // callback function for snapshot (used if no user_callback parameter given to snap function)
  56. user_canvas: null // user provided canvas for snapshot (used if no user_canvas parameter given to snap function)
  57. },
  58. errors: {
  59. FlashError: FlashError,
  60. WebcamError: WebcamError
  61. },
  62. hooks: {}, // callback hook functions
  63. init: function() {
  64. // initialize, check for getUserMedia support
  65. var self = this;
  66. // Setup getUserMedia, with polyfill for older browsers
  67. // Adapted from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
  68. this.mediaDevices = (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) ?
  69. navigator.mediaDevices : ((navigator.mozGetUserMedia || navigator.webkitGetUserMedia) ? {
  70. getUserMedia: function(c) {
  71. return new Promise(function(y, n) {
  72. (navigator.mozGetUserMedia ||
  73. navigator.webkitGetUserMedia).call(navigator, c, y, n);
  74. });
  75. }
  76. } : null);
  77. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  78. this.userMedia = this.userMedia && !!this.mediaDevices && !!window.URL;
  79. // Older versions of firefox (< 21) apparently claim support but user media does not actually work
  80. if (navigator.userAgent.match(/Firefox\D+(\d+)/)) {
  81. if (parseInt(RegExp.$1, 10) < 21) this.userMedia = null;
  82. }
  83. // Make sure media stream is closed when navigating away from page
  84. if (this.userMedia) {
  85. window.addEventListener( 'beforeunload', function(event) {
  86. self.reset();
  87. } );
  88. }
  89. },
  90. exifOrientation: function(binFile) {
  91. // extract orientation information from the image provided by iOS
  92. // algorithm based on exif-js
  93. var dataView = new DataView(binFile);
  94. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  95. console.log('Not a valid JPEG file');
  96. return 0;
  97. }
  98. var offset = 2;
  99. var marker = null;
  100. while (offset < binFile.byteLength) {
  101. // find 0xFFE1 (225 marker)
  102. if (dataView.getUint8(offset) != 0xFF) {
  103. console.log('Not a valid marker at offset ' + offset + ', found: ' + dataView.getUint8(offset));
  104. return 0;
  105. }
  106. marker = dataView.getUint8(offset + 1);
  107. if (marker == 225) {
  108. offset += 4;
  109. var str = "";
  110. for (n = 0; n < 4; n++) {
  111. str += String.fromCharCode(dataView.getUint8(offset+n));
  112. }
  113. if (str != 'Exif') {
  114. console.log('Not valid EXIF data found');
  115. return 0;
  116. }
  117. offset += 6; // tiffOffset
  118. var bigEnd = null;
  119. // test for TIFF validity and endianness
  120. if (dataView.getUint16(offset) == 0x4949) {
  121. bigEnd = false;
  122. } else if (dataView.getUint16(offset) == 0x4D4D) {
  123. bigEnd = true;
  124. } else {
  125. console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  126. return 0;
  127. }
  128. if (dataView.getUint16(offset+2, !bigEnd) != 0x002A) {
  129. console.log("Not valid TIFF data! (no 0x002A)");
  130. return 0;
  131. }
  132. var firstIFDOffset = dataView.getUint32(offset+4, !bigEnd);
  133. if (firstIFDOffset < 0x00000008) {
  134. console.log("Not valid TIFF data! (First offset less than 8)", dataView.getUint32(offset+4, !bigEnd));
  135. return 0;
  136. }
  137. // extract orientation data
  138. var dataStart = offset + firstIFDOffset;
  139. var entries = dataView.getUint16(dataStart, !bigEnd);
  140. for (var i=0; i<entries; i++) {
  141. var entryOffset = dataStart + i*12 + 2;
  142. if (dataView.getUint16(entryOffset, !bigEnd) == 0x0112) {
  143. var valueType = dataView.getUint16(entryOffset+2, !bigEnd);
  144. var numValues = dataView.getUint32(entryOffset+4, !bigEnd);
  145. if (valueType != 3 && numValues != 1) {
  146. console.log('Invalid EXIF orientation value type ('+valueType+') or count ('+numValues+')');
  147. return 0;
  148. }
  149. var value = dataView.getUint16(entryOffset + 8, !bigEnd);
  150. if (value < 1 || value > 8) {
  151. console.log('Invalid EXIF orientation value ('+value+')');
  152. return 0;
  153. }
  154. return value;
  155. }
  156. }
  157. } else {
  158. offset += 2+dataView.getUint16(offset+2);
  159. }
  160. }
  161. return 0;
  162. },
  163. fixOrientation: function(origObjURL, orientation, targetImg) {
  164. // fix image orientation based on exif orientation data
  165. // exif orientation information
  166. // http://www.impulseadventure.com/photo/exif-orientation.html
  167. // link source wikipedia (https://en.wikipedia.org/wiki/Exif#cite_note-20)
  168. var img = new Image();
  169. img.addEventListener('load', function(event) {
  170. var canvas = document.createElement('canvas');
  171. var ctx = canvas.getContext('2d');
  172. // switch width height if orientation needed
  173. if (orientation < 5) {
  174. canvas.width = img.width;
  175. canvas.height = img.height;
  176. } else {
  177. canvas.width = img.height;
  178. canvas.height = img.width;
  179. }
  180. // transform (rotate) image - see link at beginning this method
  181. switch (orientation) {
  182. case 2: ctx.transform(-1, 0, 0, 1, img.width, 0); break;
  183. case 3: ctx.transform(-1, 0, 0, -1, img.width, img.height); break;
  184. case 4: ctx.transform(1, 0, 0, -1, 0, img.height); break;
  185. case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
  186. case 6: ctx.transform(0, 1, -1, 0, img.height , 0); break;
  187. case 7: ctx.transform(0, -1, -1, 0, img.height, img.width); break;
  188. case 8: ctx.transform(0, -1, 1, 0, 0, img.width); break;
  189. }
  190. ctx.drawImage(img, 0, 0);
  191. // pass rotated image data to the target image container
  192. targetImg.src = canvas.toDataURL();
  193. }, false);
  194. // start transformation by load event
  195. img.src = origObjURL;
  196. },
  197. attach: function(elem) {
  198. // create webcam preview and attach to DOM element
  199. // pass in actual DOM reference, ID, or CSS selector
  200. if (typeof(elem) == 'string') {
  201. elem = document.getElementById(elem) || document.querySelector(elem);
  202. }
  203. if (!elem) {
  204. return this.dispatch('error', new WebcamError("Could not locate DOM element to attach to."));
  205. }
  206. this.container = elem;
  207. elem.innerHTML = ''; // start with empty element
  208. // insert "peg" so we can insert our preview canvas adjacent to it later on
  209. var peg = document.createElement('div');
  210. elem.appendChild( peg );
  211. this.peg = peg;
  212. // set width/height if not already set
  213. if (!this.params.width) this.params.width = elem.offsetWidth;
  214. if (!this.params.height) this.params.height = elem.offsetHeight;
  215. // make sure we have a nonzero width and height at this point
  216. if (!this.params.width || !this.params.height) {
  217. return this.dispatch('error', new WebcamError("No width and/or height for webcam. Please call set() first, or attach to a visible element."));
  218. }
  219. // set defaults for dest_width / dest_height if not set
  220. if (!this.params.dest_width) this.params.dest_width = this.params.width;
  221. if (!this.params.dest_height) this.params.dest_height = this.params.height;
  222. this.userMedia = _userMedia === undefined ? this.userMedia : _userMedia;
  223. // if force_flash is set, disable userMedia
  224. if (this.params.force_flash) {
  225. _userMedia = this.userMedia;
  226. this.userMedia = null;
  227. }
  228. // check for default fps
  229. if (typeof this.params.fps !== "number") this.params.fps = 30;
  230. // adjust scale if dest_width or dest_height is different
  231. var scaleX = this.params.width / this.params.dest_width;
  232. var scaleY = this.params.height / this.params.dest_height;
  233. if (this.userMedia) {
  234. // setup webcam video container
  235. var video = document.createElement('video');
  236. video.setAttribute('autoplay', 'autoplay');
  237. video.style.width = '' + this.params.dest_width + 'px';
  238. video.style.height = '' + this.params.dest_height + 'px';
  239. if ((scaleX != 1.0) || (scaleY != 1.0)) {
  240. elem.style.overflow = 'hidden';
  241. video.style.webkitTransformOrigin = '0px 0px';
  242. video.style.mozTransformOrigin = '0px 0px';
  243. video.style.msTransformOrigin = '0px 0px';
  244. video.style.oTransformOrigin = '0px 0px';
  245. video.style.transformOrigin = '0px 0px';
  246. video.style.webkitTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  247. video.style.mozTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  248. video.style.msTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  249. video.style.oTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  250. video.style.transform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  251. }
  252. // add video element to dom
  253. elem.appendChild( video );
  254. this.video = video;
  255. // ask user for access to their camera
  256. var self = this;
  257. this.mediaDevices.getUserMedia({
  258. "audio": false,
  259. "video": this.params.constraints || {
  260. mandatory: {
  261. minWidth: this.params.dest_width,
  262. minHeight: this.params.dest_height
  263. }
  264. }
  265. })
  266. .then( function(stream) {
  267. // got access, attach stream to video
  268. video.onloadedmetadata = function(e) {
  269. self.stream = stream;
  270. self.loaded = true;
  271. self.live = true;
  272. self.dispatch('load');
  273. self.dispatch('live');
  274. self.flip();
  275. };
  276. video.src = window.URL.createObjectURL( stream ) || stream;
  277. })
  278. .catch( function(err) {
  279. // JH 2016-07-31 Instead of dispatching error, now falling back to Flash if userMedia fails (thx @john2014)
  280. // JH 2016-08-07 But only if flash is actually installed -- if not, dispatch error here and now.
  281. if (self.params.enable_flash && self.detectFlash()) {
  282. setTimeout( function() { self.params.force_flash = 1; self.attach(elem); }, 1 );
  283. }
  284. else {
  285. self.dispatch('error', err);
  286. }
  287. });
  288. }
  289. else if (this.iOS) {
  290. // prepare HTML elements
  291. var div = document.createElement('div');
  292. div.id = this.container.id+'-ios_div';
  293. div.className = 'webcamjs-ios-placeholder';
  294. div.style.width = '' + this.params.width + 'px';
  295. div.style.height = '' + this.params.height + 'px';
  296. div.style.textAlign = 'center';
  297. div.style.display = 'table-cell';
  298. div.style.verticalAlign = 'middle';
  299. div.style.backgroundRepeat = 'no-repeat';
  300. div.style.backgroundSize = 'contain';
  301. div.style.backgroundPosition = 'center';
  302. var span = document.createElement('span');
  303. span.className = 'webcamjs-ios-text';
  304. span.innerHTML = this.params.iosPlaceholderText;
  305. div.appendChild(span);
  306. var img = document.createElement('img');
  307. img.id = this.container.id+'-ios_img';
  308. img.style.width = '' + this.params.dest_width + 'px';
  309. img.style.height = '' + this.params.dest_height + 'px';
  310. img.style.display = 'none';
  311. div.appendChild(img);
  312. var input = document.createElement('input');
  313. input.id = this.container.id+'-ios_input';
  314. input.setAttribute('type', 'file');
  315. input.setAttribute('accept', 'image/*');
  316. input.setAttribute('capture', 'camera');
  317. var self = this;
  318. var params = this.params;
  319. // add input listener to load the selected image
  320. input.addEventListener('change', function(event) {
  321. if (event.target.files.length > 0 && event.target.files[0].type.indexOf('image/') == 0) {
  322. var objURL = URL.createObjectURL(event.target.files[0]);
  323. // load image with auto scale and crop
  324. var image = new Image();
  325. image.addEventListener('load', function(event) {
  326. var canvas = document.createElement('canvas');
  327. canvas.width = params.dest_width;
  328. canvas.height = params.dest_height;
  329. var ctx = canvas.getContext('2d');
  330. // crop and scale image for final size
  331. ratio = Math.min(image.width / params.dest_width, image.height / params.dest_height);
  332. var sw = params.dest_width * ratio;
  333. var sh = params.dest_height * ratio;
  334. var sx = (image.width - sw) / 2;
  335. var sy = (image.height - sh) / 2;
  336. ctx.drawImage(image, sx, sy, sw, sh, 0, 0, params.dest_width, params.dest_height);
  337. var dataURL = canvas.toDataURL();
  338. img.src = dataURL;
  339. div.style.backgroundImage = "url('"+dataURL+"')";
  340. }, false);
  341. // read EXIF data
  342. var fileReader = new FileReader();
  343. fileReader.addEventListener('load', function(e) {
  344. var orientation = self.exifOrientation(e.target.result);
  345. if (orientation > 1) {
  346. // image need to rotate (see comments on fixOrientation method for more information)
  347. // transform image and load to image object
  348. self.fixOrientation(objURL, orientation, image);
  349. } else {
  350. // load image data to image object
  351. image.src = objURL;
  352. }
  353. }, false);
  354. // Convert image data to blob format
  355. var http = new XMLHttpRequest();
  356. http.open("GET", objURL, true);
  357. http.responseType = "blob";
  358. http.onload = function(e) {
  359. if (this.status == 200 || this.status === 0) {
  360. fileReader.readAsArrayBuffer(this.response);
  361. }
  362. };
  363. http.send();
  364. }
  365. }, false);
  366. input.style.display = 'none';
  367. elem.appendChild(input);
  368. // make div clickable for open camera interface
  369. div.addEventListener('click', function(event) {
  370. if (params.user_callback) {
  371. // global user_callback defined - create the snapshot
  372. self.snap(params.user_callback, params.user_canvas);
  373. } else {
  374. // no global callback definied for snapshot, load image and wait for external snap method call
  375. input.style.display = 'block';
  376. input.focus();
  377. input.click();
  378. input.style.display = 'none';
  379. }
  380. }, false);
  381. elem.appendChild(div);
  382. this.loaded = true;
  383. this.live = true;
  384. }
  385. else if (this.params.enable_flash && this.detectFlash()) {
  386. // flash fallback
  387. window.Webcam = Webcam; // needed for flash-to-js interface
  388. var div = document.createElement('div');
  389. div.innerHTML = this.getSWFHTML();
  390. elem.appendChild( div );
  391. }
  392. else {
  393. this.dispatch('error', new WebcamError( this.params.noInterfaceFoundText ));
  394. }
  395. // setup final crop for live preview
  396. if (this.params.crop_width && this.params.crop_height) {
  397. var scaled_crop_width = Math.floor( this.params.crop_width * scaleX );
  398. var scaled_crop_height = Math.floor( this.params.crop_height * scaleY );
  399. elem.style.width = '' + scaled_crop_width + 'px';
  400. elem.style.height = '' + scaled_crop_height + 'px';
  401. elem.style.overflow = 'hidden';
  402. elem.scrollLeft = Math.floor( (this.params.width / 2) - (scaled_crop_width / 2) );
  403. elem.scrollTop = Math.floor( (this.params.height / 2) - (scaled_crop_height / 2) );
  404. }
  405. else {
  406. // no crop, set size to desired
  407. elem.style.width = '' + this.params.width + 'px';
  408. elem.style.height = '' + this.params.height + 'px';
  409. }
  410. },
  411. reset: function() {
  412. // shutdown camera, reset to potentially attach again
  413. if (this.preview_active) this.unfreeze();
  414. // attempt to fix issue #64
  415. this.unflip();
  416. if (this.userMedia) {
  417. if (this.stream) {
  418. if (this.stream.getVideoTracks) {
  419. // get video track to call stop on it
  420. var tracks = this.stream.getVideoTracks();
  421. if (tracks && tracks[0] && tracks[0].stop) tracks[0].stop();
  422. }
  423. else if (this.stream.stop) {
  424. // deprecated, may be removed in future
  425. this.stream.stop();
  426. }
  427. }
  428. delete this.stream;
  429. delete this.video;
  430. }
  431. if ((this.userMedia !== true) && this.loaded && !this.iOS) {
  432. // call for turn off camera in flash
  433. var movie = this.getMovie();
  434. if (movie && movie._releaseCamera) movie._releaseCamera();
  435. }
  436. if (this.container) {
  437. this.container.innerHTML = '';
  438. delete this.container;
  439. }
  440. this.loaded = false;
  441. this.live = false;
  442. },
  443. set: function() {
  444. // set one or more params
  445. // variable argument list: 1 param = hash, 2 params = key, value
  446. if (arguments.length == 1) {
  447. for (var key in arguments[0]) {
  448. this.params[key] = arguments[0][key];
  449. }
  450. }
  451. else {
  452. this.params[ arguments[0] ] = arguments[1];
  453. }
  454. },
  455. on: function(name, callback) {
  456. // set callback hook
  457. name = name.replace(/^on/i, '').toLowerCase();
  458. if (!this.hooks[name]) this.hooks[name] = [];
  459. this.hooks[name].push( callback );
  460. },
  461. off: function(name, callback) {
  462. // remove callback hook
  463. name = name.replace(/^on/i, '').toLowerCase();
  464. if (this.hooks[name]) {
  465. if (callback) {
  466. // remove one selected callback from list
  467. var idx = this.hooks[name].indexOf(callback);
  468. if (idx > -1) this.hooks[name].splice(idx, 1);
  469. }
  470. else {
  471. // no callback specified, so clear all
  472. this.hooks[name] = [];
  473. }
  474. }
  475. },
  476. dispatch: function() {
  477. // fire hook callback, passing optional value to it
  478. var name = arguments[0].replace(/^on/i, '').toLowerCase();
  479. var args = Array.prototype.slice.call(arguments, 1);
  480. if (this.hooks[name] && this.hooks[name].length) {
  481. for (var idx = 0, len = this.hooks[name].length; idx < len; idx++) {
  482. var hook = this.hooks[name][idx];
  483. if (typeof(hook) == 'function') {
  484. // callback is function reference, call directly
  485. hook.apply(this, args);
  486. }
  487. else if ((typeof(hook) == 'object') && (hook.length == 2)) {
  488. // callback is PHP-style object instance method
  489. hook[0][hook[1]].apply(hook[0], args);
  490. }
  491. else if (window[hook]) {
  492. // callback is global function name
  493. window[ hook ].apply(window, args);
  494. }
  495. } // loop
  496. return true;
  497. }
  498. else if (name == 'error') {
  499. if ((args[0] instanceof FlashError) || (args[0] instanceof WebcamError)) {
  500. message = args[0].message;
  501. } else {
  502. message = "Could not access webcam: " + args[0].name + ": " +
  503. args[0].message + " " + args[0].toString();
  504. }
  505. // default error handler if no custom one specified
  506. alert("Webcam.js Error: " + message);
  507. }
  508. return false; // no hook defined
  509. },
  510. setSWFLocation: function(value) {
  511. // for backward compatibility.
  512. this.set('swfURL', value);
  513. },
  514. detectFlash: function() {
  515. // return true if browser supports flash, false otherwise
  516. // Code snippet borrowed from: https://github.com/swfobject/swfobject
  517. var SHOCKWAVE_FLASH = "Shockwave Flash",
  518. SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
  519. FLASH_MIME_TYPE = "application/x-shockwave-flash",
  520. win = window,
  521. nav = navigator,
  522. hasFlash = false;
  523. if (typeof nav.plugins !== "undefined" && typeof nav.plugins[SHOCKWAVE_FLASH] === "object") {
  524. var desc = nav.plugins[SHOCKWAVE_FLASH].description;
  525. if (desc && (typeof nav.mimeTypes !== "undefined" && nav.mimeTypes[FLASH_MIME_TYPE] && nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) {
  526. hasFlash = true;
  527. }
  528. }
  529. else if (typeof win.ActiveXObject !== "undefined") {
  530. try {
  531. var ax = new ActiveXObject(SHOCKWAVE_FLASH_AX);
  532. if (ax) {
  533. var ver = ax.GetVariable("$version");
  534. if (ver) hasFlash = true;
  535. }
  536. }
  537. catch (e) {;}
  538. }
  539. return hasFlash;
  540. },
  541. getSWFHTML: function() {
  542. // Return HTML for embedding flash based webcam capture movie
  543. var html = '',
  544. swfURL = this.params.swfURL;
  545. // make sure we aren't running locally (flash doesn't work)
  546. if (location.protocol.match(/file/)) {
  547. this.dispatch('error', new FlashError("Flash does not work from local disk. Please run from a web server."));
  548. return '<h3 style="color:red">ERROR: the Webcam.js Flash fallback does not work from local disk. Please run it from a web server.</h3>';
  549. }
  550. // make sure we have flash
  551. if (!this.detectFlash()) {
  552. this.dispatch('error', new FlashError("Adobe Flash Player not found. Please install from get.adobe.com/flashplayer and try again."));
  553. return '<h3 style="color:red">' + this.params.flashNotDetectedText + '</h3>';
  554. }
  555. // set default swfURL if not explicitly set
  556. if (!swfURL) {
  557. // find our script tag, and use that base URL
  558. var base_url = '';
  559. var scpts = document.getElementsByTagName('script');
  560. for (var idx = 0, len = scpts.length; idx < len; idx++) {
  561. var src = scpts[idx].getAttribute('src');
  562. if (src && src.match(/\/webcam(\.min)?\.js/)) {
  563. base_url = src.replace(/\/webcam(\.min)?\.js.*$/, '');
  564. idx = len;
  565. }
  566. }
  567. if (base_url) swfURL = base_url + '/webcam.swf';
  568. else swfURL = 'webcam.swf';
  569. }
  570. // if this is the user's first visit, set flashvar so flash privacy settings panel is shown first
  571. if (window.localStorage && !localStorage.getItem('visited')) {
  572. this.params.new_user = 1;
  573. localStorage.setItem('visited', 1);
  574. }
  575. // construct flashvars string
  576. var flashvars = '';
  577. for (var key in this.params) {
  578. if (flashvars) flashvars += '&';
  579. flashvars += key + '=' + escape(this.params[key]);
  580. }
  581. // construct object/embed tag
  582. html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" type="application/x-shockwave-flash" codebase="'+this.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+this.params.width+'" height="'+this.params.height+'" id="webcam_movie_obj" align="middle"><param name="wmode" value="opaque" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+swfURL+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><embed id="webcam_movie_embed" src="'+swfURL+'" wmode="opaque" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+this.params.width+'" height="'+this.params.height+'" name="webcam_movie_embed" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'"></embed></object>';
  583. return html;
  584. },
  585. getMovie: function() {
  586. // get reference to movie object/embed in DOM
  587. if (!this.loaded) return this.dispatch('error', new FlashError("Flash Movie is not loaded yet"));
  588. var movie = document.getElementById('webcam_movie_obj');
  589. if (!movie || !movie._snap) movie = document.getElementById('webcam_movie_embed');
  590. if (!movie) this.dispatch('error', new FlashError("Cannot locate Flash movie in DOM"));
  591. return movie;
  592. },
  593. freeze: function() {
  594. // show preview, freeze camera
  595. var self = this;
  596. var params = this.params;
  597. // kill preview if already active
  598. if (this.preview_active) this.unfreeze();
  599. // determine scale factor
  600. var scaleX = this.params.width / this.params.dest_width;
  601. var scaleY = this.params.height / this.params.dest_height;
  602. // must unflip container as preview canvas will be pre-flipped
  603. this.unflip();
  604. // calc final size of image
  605. var final_width = params.crop_width || params.dest_width;
  606. var final_height = params.crop_height || params.dest_height;
  607. // create canvas for holding preview
  608. var preview_canvas = document.createElement('canvas');
  609. preview_canvas.width = final_width;
  610. preview_canvas.height = final_height;
  611. var preview_context = preview_canvas.getContext('2d');
  612. // save for later use
  613. this.preview_canvas = preview_canvas;
  614. this.preview_context = preview_context;
  615. // scale for preview size
  616. if ((scaleX != 1.0) || (scaleY != 1.0)) {
  617. preview_canvas.style.webkitTransformOrigin = '0px 0px';
  618. preview_canvas.style.mozTransformOrigin = '0px 0px';
  619. preview_canvas.style.msTransformOrigin = '0px 0px';
  620. preview_canvas.style.oTransformOrigin = '0px 0px';
  621. preview_canvas.style.transformOrigin = '0px 0px';
  622. preview_canvas.style.webkitTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  623. preview_canvas.style.mozTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  624. preview_canvas.style.msTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  625. preview_canvas.style.oTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  626. preview_canvas.style.transform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
  627. }
  628. // take snapshot, but fire our own callback
  629. this.snap( function() {
  630. // add preview image to dom, adjust for crop
  631. preview_canvas.style.position = 'relative';
  632. preview_canvas.style.left = '' + self.container.scrollLeft + 'px';
  633. preview_canvas.style.top = '' + self.container.scrollTop + 'px';
  634. self.container.insertBefore( preview_canvas, self.peg );
  635. self.container.style.overflow = 'hidden';
  636. // set flag for user capture (use preview)
  637. self.preview_active = true;
  638. }, preview_canvas );
  639. },
  640. unfreeze: function() {
  641. // cancel preview and resume live video feed
  642. if (this.preview_active) {
  643. // remove preview canvas
  644. this.container.removeChild( this.preview_canvas );
  645. delete this.preview_context;
  646. delete this.preview_canvas;
  647. // unflag
  648. this.preview_active = false;
  649. // re-flip if we unflipped before
  650. this.flip();
  651. }
  652. },
  653. flip: function() {
  654. // flip container horiz (mirror mode) if desired
  655. if (this.params.flip_horiz) {
  656. var sty = this.container.style;
  657. sty.webkitTransform = 'scaleX(-1)';
  658. sty.mozTransform = 'scaleX(-1)';
  659. sty.msTransform = 'scaleX(-1)';
  660. sty.oTransform = 'scaleX(-1)';
  661. sty.transform = 'scaleX(-1)';
  662. sty.filter = 'FlipH';
  663. sty.msFilter = 'FlipH';
  664. }
  665. },
  666. unflip: function() {
  667. // unflip container horiz (mirror mode) if desired
  668. if (this.params.flip_horiz) {
  669. var sty = this.container.style;
  670. sty.webkitTransform = 'scaleX(1)';
  671. sty.mozTransform = 'scaleX(1)';
  672. sty.msTransform = 'scaleX(1)';
  673. sty.oTransform = 'scaleX(1)';
  674. sty.transform = 'scaleX(1)';
  675. sty.filter = '';
  676. sty.msFilter = '';
  677. }
  678. },
  679. savePreview: function(user_callback, user_canvas) {
  680. // save preview freeze and fire user callback
  681. var params = this.params;
  682. var canvas = this.preview_canvas;
  683. var context = this.preview_context;
  684. // render to user canvas if desired
  685. if (user_canvas) {
  686. var user_context = user_canvas.getContext('2d');
  687. user_context.drawImage( canvas, 0, 0 );
  688. }
  689. // fire user callback if desired
  690. user_callback(
  691. user_canvas ? null : canvas.toDataURL('image/' + params.image_format, params.jpeg_quality / 100 ),
  692. canvas,
  693. context
  694. );
  695. // remove preview
  696. if (this.params.unfreeze_snap) this.unfreeze();
  697. },
  698. snap: function(user_callback, user_canvas) {
  699. // use global callback and canvas if not defined as parameter
  700. if (!user_callback) user_callback = this.params.user_callback;
  701. if (!user_canvas) user_canvas = this.params.user_canvas;
  702. // take snapshot and return image data uri
  703. var self = this;
  704. var params = this.params;
  705. if (!this.loaded) return this.dispatch('error', new WebcamError("Webcam is not loaded yet"));
  706. // if (!this.live) return this.dispatch('error', new WebcamError("Webcam is not live yet"));
  707. if (!user_callback) return this.dispatch('error', new WebcamError("Please provide a callback function or canvas to snap()"));
  708. // if we have an active preview freeze, use that
  709. if (this.preview_active) {
  710. this.savePreview( user_callback, user_canvas );
  711. return null;
  712. }
  713. // create offscreen canvas element to hold pixels
  714. var canvas = document.createElement('canvas');
  715. canvas.width = this.params.dest_width;
  716. canvas.height = this.params.dest_height;
  717. var context = canvas.getContext('2d');
  718. // flip canvas horizontally if desired
  719. if (this.params.flip_horiz) {
  720. context.translate( params.dest_width, 0 );
  721. context.scale( -1, 1 );
  722. }
  723. // create inline function, called after image load (flash) or immediately (native)
  724. var func = function() {
  725. // render image if needed (flash)
  726. if (this.src && this.width && this.height) {
  727. context.drawImage(this, 0, 0, params.dest_width, params.dest_height);
  728. }
  729. // crop if desired
  730. if (params.crop_width && params.crop_height) {
  731. var crop_canvas = document.createElement('canvas');
  732. crop_canvas.width = params.crop_width;
  733. crop_canvas.height = params.crop_height;
  734. var crop_context = crop_canvas.getContext('2d');
  735. crop_context.drawImage( canvas,
  736. Math.floor( (params.dest_width / 2) - (params.crop_width / 2) ),
  737. Math.floor( (params.dest_height / 2) - (params.crop_height / 2) ),
  738. params.crop_width,
  739. params.crop_height,
  740. 0,
  741. 0,
  742. params.crop_width,
  743. params.crop_height
  744. );
  745. // swap canvases
  746. context = crop_context;
  747. canvas = crop_canvas;
  748. }
  749. // render to user canvas if desired
  750. if (user_canvas) {
  751. var user_context = user_canvas.getContext('2d');
  752. user_context.drawImage( canvas, 0, 0 );
  753. }
  754. // fire user callback if desired
  755. user_callback(
  756. user_canvas ? null : canvas.toDataURL('image/' + params.image_format, params.jpeg_quality / 100 ),
  757. canvas,
  758. context
  759. );
  760. };
  761. // grab image frame from userMedia or flash movie
  762. if (this.userMedia) {
  763. // native implementation
  764. context.drawImage(this.video, 0, 0, this.params.dest_width, this.params.dest_height);
  765. // fire callback right away
  766. func();
  767. }
  768. else if (this.iOS) {
  769. var div = document.getElementById(this.container.id+'-ios_div');
  770. var img = document.getElementById(this.container.id+'-ios_img');
  771. var input = document.getElementById(this.container.id+'-ios_input');
  772. // function for handle snapshot event (call user_callback and reset the interface)
  773. iFunc = function(event) {
  774. func.call(img);
  775. img.removeEventListener('load', iFunc);
  776. div.style.backgroundImage = 'none';
  777. img.removeAttribute('src');
  778. input.value = null;
  779. };
  780. if (!input.value) {
  781. // No image selected yet, activate input field
  782. img.addEventListener('load', iFunc);
  783. input.style.display = 'block';
  784. input.focus();
  785. input.click();
  786. input.style.display = 'none';
  787. } else {
  788. // Image already selected
  789. iFunc(null);
  790. }
  791. }
  792. else {
  793. // flash fallback
  794. var raw_data = this.getMovie()._snap();
  795. // render to image, fire callback when complete
  796. var img = new Image();
  797. img.onload = func;
  798. img.src = 'data:image/'+this.params.image_format+';base64,' + raw_data;
  799. }
  800. return null;
  801. },
  802. configure: function(panel) {
  803. // open flash configuration panel -- specify tab name:
  804. // "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
  805. if (!panel) panel = "camera";
  806. this.getMovie()._configure(panel);
  807. },
  808. flashNotify: function(type, msg) {
  809. // receive notification from flash about event
  810. switch (type) {
  811. case 'flashLoadComplete':
  812. // movie loaded successfully
  813. this.loaded = true;
  814. this.dispatch('load');
  815. break;
  816. case 'cameraLive':
  817. // camera is live and ready to snap
  818. this.live = true;
  819. this.dispatch('live');
  820. break;
  821. case 'error':
  822. // Flash error
  823. this.dispatch('error', new FlashError(msg));
  824. break;
  825. default:
  826. // catch-all event, just in case
  827. // console.log("webcam flash_notify: " + type + ": " + msg);
  828. break;
  829. }
  830. },
  831. b64ToUint6: function(nChr) {
  832. // convert base64 encoded character to 6-bit integer
  833. // from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
  834. return nChr > 64 && nChr < 91 ? nChr - 65
  835. : nChr > 96 && nChr < 123 ? nChr - 71
  836. : nChr > 47 && nChr < 58 ? nChr + 4
  837. : nChr === 43 ? 62 : nChr === 47 ? 63 : 0;
  838. },
  839. base64DecToArr: function(sBase64, nBlocksSize) {
  840. // convert base64 encoded string to Uintarray
  841. // from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
  842. var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
  843. nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2,
  844. taBytes = new Uint8Array(nOutLen);
  845. for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
  846. nMod4 = nInIdx & 3;
  847. nUint24 |= this.b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
  848. if (nMod4 === 3 || nInLen - nInIdx === 1) {
  849. for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
  850. taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
  851. }
  852. nUint24 = 0;
  853. }
  854. }
  855. return taBytes;
  856. },
  857. upload: function(image_data_uri, target_url, callback) {
  858. // submit image data to server using binary AJAX
  859. var form_elem_name = this.params.upload_name || 'webcam';
  860. // detect image format from within image_data_uri
  861. var image_fmt = '';
  862. if (image_data_uri.match(/^data\:image\/(\w+)/))
  863. image_fmt = RegExp.$1;
  864. else
  865. throw "Cannot locate image format in Data URI";
  866. // extract raw base64 data from Data URI
  867. var raw_image_data = image_data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
  868. // contruct use AJAX object
  869. var http = new XMLHttpRequest();
  870. http.open("POST", target_url, true);
  871. // setup progress events
  872. if (http.upload && http.upload.addEventListener) {
  873. http.upload.addEventListener( 'progress', function(e) {
  874. if (e.lengthComputable) {
  875. var progress = e.loaded / e.total;
  876. Webcam.dispatch('uploadProgress', progress, e);
  877. }
  878. }, false );
  879. }
  880. // completion handler
  881. var self = this;
  882. http.onload = function() {
  883. if (callback) callback.apply( self, [http.status, http.responseText, http.statusText] );
  884. Webcam.dispatch('uploadComplete', http.status, http.responseText, http.statusText);
  885. };
  886. // create a blob and decode our base64 to binary
  887. var blob = new Blob( [ this.base64DecToArr(raw_image_data) ], {type: 'image/'+image_fmt} );
  888. // stuff into a form, so servers can easily receive it as a standard file upload
  889. var form = new FormData();
  890. form.append( form_elem_name, blob, form_elem_name+"."+image_fmt.replace(/e/, '') );
  891. // send data to server
  892. http.send(form);
  893. }
  894. };
  895. Webcam.init();
  896. if (typeof define === 'function' && define.amd) {
  897. define( function() { return Webcam; } );
  898. }
  899. else if (typeof module === 'object' && module.exports) {
  900. module.exports = Webcam;
  901. }
  902. else {
  903. window.Webcam = Webcam;
  904. }
  905. }(window));