forked from mikkoh/webcamjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webcam.js
531 lines (421 loc) · 16.6 KB
/
webcam.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// WebcamJS v1.0
// Webcam library for capturing JPEG/PNG images in JavaScript
// Attempts getUserMedia, falls back to Flash
// Author: Joseph Huckaby: http://github.com/jhuckaby
// Based on JPEGCam: http://code.google.com/p/jpegcam/
// Copyright (c) 2012 Joseph Huckaby
// Licensed under the MIT License
/* Usage:
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script language="JavaScript">
Webcam.attach( '#my_camera' );
function take_snapshot() {
var data_uri = Webcam.snap();
document.getElementById('my_result').innerHTML =
'<img src="'+data_uri+'"/>';
}
</script>
<a href="javascript:void(take_snapshot())">Take Snapshot</a>
*/
var Webcam = {
version: '1.0.0',
// globals
protocol: location.protocol.match(/https/i) ? 'https' : 'http',
swfURL: '', // URI to webcam.swf movie (defaults to cwd)
loaded: false, // true when webcam movie finishes loading
live: false, // true when webcam is initialized and ready to snap
userMedia: true, // true when getUserMedia is supported natively,
highResCaptures: {},
hooks: {
load: null,
live: null,
uploadcomplete: null,
uploadprogress: null,
error: function(msg) { alert("Webcam.js Error: " + msg); }
}, // callback hook functions
init: function() {
// initialize, check for getUserMedia support
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
this.userMedia = this.userMedia && !!navigator.getUserMedia && !!window.URL;
// Older versions of firefox (< 21) apparently claim support but user media does not actually work
if (navigator.userAgent.match(/Firefox\D+(\d+)/)) {
if (parseInt(RegExp.$1, 10) < 21) this.userMedia = null;
}
},
attach: function(elem) {
// create webcam preview and attach to DOM element
// pass in actual DOM reference, ID, or CSS selector
if (typeof(elem) == 'string') {
elem = document.getElementById(elem) || document.querySelector(elem);
}
if (!elem) {
return this.dispatch('error', "Could not locate DOM element to attach to.");
}
this.container = elem;
if (!this.params.width) this.params.width = elem.offsetWidth;
if (!this.params.height) this.params.height = elem.offsetHeight;
// set defaults for dest_width / dest_height if not set
if (!this.params.dest_width) this.params.dest_width = this.params.width;
if (!this.params.dest_height) this.params.dest_height = this.params.height;
// if force_flash is set, disable userMedia
if (this.params.force_flash) this.userMedia = null;
if (this.userMedia) {
// setup webcam video container
var video = document.createElement('video');
video.setAttribute('autoplay', 'autoplay');
// video.style.width = '' + this.params.dest_width + 'px';
// video.style.height = '' + this.params.dest_height + 'px';
// adjust scale if dest_width or dest_height is different
// var scaleX = this.params.width / this.params.dest_width;
// var scaleY = this.params.height / this.params.dest_height;
// if ((scaleX != 1.0) || (scaleY != 1.0)) {
// elem.style.overflow = 'visible';
// video.style.webkitTransformOrigin = '0px 0px';
// video.style.mozTransformOrigin = '0px 0px';
// video.style.msTransformOrigin = '0px 0px';
// video.style.oTransformOrigin = '0px 0px';
// video.style.transformOrigin = '0px 0px';
// video.style.webkitTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
// video.style.mozTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
// video.style.msTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
// video.style.oTransform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
// video.style.transform = 'scaleX('+scaleX+') scaleY('+scaleY+')';
// }
// add video element to dom
elem.appendChild( video );
this.video = video;
// create offscreen canvas element to hold pixels later on
var canvas = document.createElement('canvas');
// canvas.width = this.params.dest_width;
// canvas.height = this.params.dest_height;
var context = canvas.getContext('2d');
this.context = context;
this.canvas = canvas;
// ask user for access to their camera
var self = this;
navigator.getUserMedia({
audio: this.params.audio || false,
video: {
mandatory: {},
optional: [
{ minWidth: this.params.width },
{ minHeight: this.params.height }
]
}
},
function(stream) {
// got access, attach stream to video
video.addEventListener( 'canplay', function() {
Webcam.loaded = true;
Webcam.live = true;
if( this.params.audio ) {
var audioContext = new AudioContext();
try {
this.audioInput = audioContext.createMediaStreamSource( stream );
this.volume = audioContext.createGain();
this.audioInput.connect( this.volume );
this.volume.connect( audioContext.destination );
this.volume.gain.value = 0;
} catch(err){
console.log(err);
}
}
var checkWidthHeight = function() {
if( video.videoWidth > 0 && video.videoHeight > 0 ) {
var scale = this.params.dest_width / this.params.width,
oWidth = this.params.dest_width;
this.params.dest_width = video.videoWidth * scale;
this.params.dest_height = video.videoHeight * scale;
if( this.params.dest_width < oWidth ) {
scale = oWidth / this.params.dest_width;
this.params.dest_width *= scale;
this.params.dest_height *= scale;
}
this.params.width = video.videoWidth;
this.params.height = video.videoHeight;
this.canvas.width = this.params.dest_width;
this.canvas.height = this.params.dest_height;
video.style.width = video.videoWidth + 'px';
video.style.height = video.videoHeight + 'px';
Webcam.dispatch('load');
Webcam.dispatch('live');
} else {
setTimeout( checkWidthHeight, 33 );
}
}.bind( this );
checkWidthHeight();
}.bind( this ));
video.src = window.URL.createObjectURL( stream ) || stream;
Webcam.stream = stream;
}.bind( this ),
function(err) {
return self.dispatch('error', "Could not access webcam.");
});
}
else {
this.movie = null;
// flash fallback
elem.innerHTML = this.getSWFHTML();
}
},
reset: function() {
// shutdown camera, reset to potentially attach again
if (this.userMedia) {
try { this.stream.stop(); } catch (e) {;}
delete this.stream;
delete this.canvas;
delete this.context;
delete this.video;
}
this.container.innerHTML = '';
delete this.container;
this.loaded = false;
this.live = false;
},
set: function( params ) {
// this.params = {
// width: params.width || 0,
// height: params.height || 0,
// dest_width: params.dest_width || 0,
// dest_height: params.dest_height || 0,
// image_format: params.image_format || 'jpeg',
// jpeg_quality: params.jpeg_quality || 90,
// force_flash: params.force_flash || false
// };
params.width = params.width || 0;
params.height = params.height || 0;
params.dest_width = params.dest_width || 0;
params.dest_height = params.dest_height || 0;
params.image_format = params.image_format || 'jpeg';
params.jpeg_quality = params.jpeg_quality || 90;
params.force_flash = params.force_flash || false;
this.params = params;
},
on: function(name, callback) {
// set callback hook
// supported hooks: onLoad, onError, onLive
name = name.replace(/^on/i, '').toLowerCase();
if (typeof(this.hooks[name]) == 'undefined')
throw "Event type not supported: " + name;
this.hooks[name] = callback;
},
dispatch: function() {
// fire hook callback, passing optional value to it
var name = arguments[0].replace(/^on/i, '').toLowerCase();
var args = Array.prototype.slice.call(arguments, 1);
if (this.hooks[name]) {
if (typeof(this.hooks[name]) == 'function') {
// callback is function reference, call directly
this.hooks[name].apply(this, args);
}
else if (typeof(this.hooks[name]) == 'array') {
// callback is PHP-style object instance method
this.hooks[name][0][this.hooks[name][1]].apply(this.hooks[name][0], args);
}
else if (window[this.hooks[name]]) {
// callback is global function name
window[ this.hooks[name] ].apply(window, args);
}
return true;
}
return false; // no hook defined
},
setSWFLocation: function(url) {
// set location of SWF movie (defaults to webcam.swf in cwd)
this.swfURL = url;
},
getSWFHTML: function() {
// Return HTML for embedding flash based webcam capture movie
var html = '';
// make sure we aren't running locally (flash doesn't work)
if (location.protocol.match(/file/)) {
return '<h1 style="color:red">Sorry, the Webcam.js Flash fallback does not work from local disk. Please upload it to a web server first.</h1>';
}
// set default swfURL if not explicitly set
if (!this.swfURL) {
// find our script tag, and use that base URL
var base_url = '';
var scpts = document.getElementsByTagName('script');
for (var idx = 0, len = scpts.length; idx < len; idx++) {
var src = scpts[idx].getAttribute('src');
if (src && src.match(/\/webcam(\.min)?\.js/)) {
base_url = src.replace(/\/webcam(\.min)?\.js.*$/, '');
idx = len;
}
}
if (base_url) this.swfURL = base_url + '/webcam.swf';
else this.swfURL = 'webcam.swf';
}
// if this is the user's first visit, set flashvar so flash privacy settings panel is shown first
if (window.localStorage && !localStorage.getItem('visited')) {
this.params.new_user = 1;
localStorage.setItem('visited', 1);
}
// construct flashvars string
var flashvars = '';
for (var key in this.params) {
if (flashvars) flashvars += '&';
flashvars += key + '=' + escape(this.params[key]);
}
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="allowScriptAccess" value="always" /><param name="wmode" value="opaque" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+this.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="'+this.swfURL+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+this.params.width+'" height="'+this.params.height+'" name="webcam_movie_embed" align="middle" allowScriptAccess="always" wmode="opaque" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'"></embed></object>';
return html;
},
getMovie: function() {
if( !this.movie ) {
if (!this.loaded) return this.dispatch('error', "Flash Movie is not loaded yet");
var movie = document.getElementById('webcam_movie_obj');
if (!movie || !movie._snap) movie = document.getElementById('webcam_movie_embed');
if (!movie) this.dispatch('error', "Cannot locate Flash movie in DOM");
this.movie = movie;
}
return this.movie;
},
saveHighRes: function( id ) {
if( this.userMedia ) {
var canvas = document.createElement( 'canvas' ),
ctx = canvas.getContext( '2d' );
this.highResCaptures[ id ] = canvas;
canvas.width = this.params.width;
canvas.height = this.params.height;
ctx.drawImage( this.video, 0, 0, canvas.width, canvas.height );
} else {
this.getMovie()._saveHighRes( id.toString() );
}
},
deleteHighRes: function( id ) {
if( this.userMedia ) {
this.highResCaptures[ id ] = undefined;
} else {
this.getMovie()._deleteHighRes( id );
}
},
getHighRes: function( id ) {
if( this.userMedia ) {
if( this.highResCaptures[ id ] )
return this.highResCaptures[ id ].toDataURL('image/' + this.params.image_format, this.params.jpeg_quality / 100 );
else
return null;
} else {
var raw_data = this.getMovie()._getHighRes( id );
if( raw_data )
return 'data:image/'+this.params.image_format+';base64,' + raw_data;
else
return null;
}
},
snap: function( doBase64 ) {
// take snapshot and return image data uri
if (!this.loaded) return this.dispatch('error', "Webcam is not loaded yet");
if (!this.live) return this.dispatch('error', "Webcam is not live yet");
if (this.userMedia) {
// native implementation
this.context.drawImage( this.video, 0, 0, this.canvas.width, this.canvas.height );
if( doBase64 )
return this.canvas.toDataURL('image/' + this.params.image_format, this.params.jpeg_quality / 100 );
}
else {
// flash fallback
if( doBase64 ) {
var raw_data = this.getMovie()._snap();
return 'data:image/'+this.params.image_format+';base64,' + raw_data;
} else {
throw 'You cannot be using the Flash fallback and pass in false for doBase64';
}
}
},
configure: function(panel) {
// open flash configuration panel -- specify tab name:
// "camera", "privacy", "default", "localStorage", "microphone", "settingsManager"
if (!panel) panel = "camera";
this.getMovie()._configure(panel);
},
flashNotify: function(type, msg) {
// receive notification from flash about event
switch (type) {
case 'flashLoadComplete':
// movie loaded successfully
this.loaded = true;
this.getMovie(); //this will ensure we have a reference always and forever
this.dispatch('load');
break;
case 'cameraLive':
// camera is live and ready to snap
this.live = true;
this.dispatch('live');
break;
case 'error':
// Flash error
this.dispatch('error', msg);
break;
default:
// catch-all event, just in case
// console.log("webcam flash_notify: " + type + ": " + msg);
break;
}
},
b64ToUint6: function(nChr) {
// convert base64 encoded character to 6-bit integer
// from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
return nChr > 64 && nChr < 91 ? nChr - 65
: nChr > 96 && nChr < 123 ? nChr - 71
: nChr > 47 && nChr < 58 ? nChr + 4
: nChr === 43 ? 62 : nChr === 47 ? 63 : 0;
},
base64DecToArr: function(sBase64, nBlocksSize) {
// convert base64 encoded string to Uintarray
// from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2,
taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= this.b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
},
upload: function(image_data_uri, target_url, callback) {
// submit image data to server using binary AJAX
if (callback) Webcam.on('uploadComplete', callback);
var form_elem_name = 'webcam';
// detect image format from within image_data_uri
var image_fmt = '';
if (image_data_uri.match(/^data\:image\/(\w+)/))
image_fmt = RegExp.$1;
else
throw "Cannot locate image format in Data URI";
// extract raw base64 data from Data URI
var raw_image_data = image_data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
// contruct use AJAX object
var http = new XMLHttpRequest();
http.open("POST", target_url, true);
// setup progress events
if (http.upload && http.upload.addEventListener) {
http.upload.addEventListener( 'progress', function(e) {
if (e.lengthComputable) {
var progress = e.loaded / e.total;
Webcam.dispatch('uploadProgress', progress, e);
}
}, false );
}
// completion handler
http.onload = function() {
Webcam.dispatch('uploadComplete', http.status, http.responseText, http.statusText);
};
// create a blob and decode our base64 to binary
var blob = new Blob( [ this.base64DecToArr(raw_image_data) ], {type: 'image/'+image_fmt} );
// stuff into a form, so servers can easily receive it as a standard file upload
var form = new FormData();
form.append( form_elem_name, blob, form_elem_name+"."+image_fmt.replace(/e/, '') );
// send data to server
http.send(form);
}
};
Webcam.init();