-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcamera.js
More file actions
111 lines (87 loc) · 2.51 KB
/
camera.js
File metadata and controls
111 lines (87 loc) · 2.51 KB
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
/*
camera.js v1.1
http://github.com/idevelop/camera.js
Author: Andrei Gheorghe (http://idevelop.github.com)
License: MIT
*/
var camera = (function() {
var options;
var video, canvas, context;
var renderTimer;
function initVideoStream() {
video = document.createElement("video");
video.setAttribute('width', options.width);
video.setAttribute('height', options.height);
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (navigator.getUserMedia) {
navigator.getUserMedia({
video: true,
}, function(stream) {
options.onSuccess();
if (video.mozSrcObject !== undefined) { // hack for Firefox < 19
video.mozSrcObject = stream;
} else {
video.srcObject = stream;
}
initCanvas();
}, options.onError);
} else {
options.onNotSupported();
}
}
function initCanvas() {
canvas = options.targetCanvas || document.createElement("canvas");
canvas.setAttribute('width', options.width);
canvas.setAttribute('height', options.height);
context = canvas.getContext('2d');
// mirror video
if (options.mirror) {
context.translate(canvas.width, 0);
context.scale(-1, 1);
}
startCapture();
}
function startCapture() {
video.play();
renderTimer = setInterval(function() {
try {
context.drawImage(video, 0, 0, video.width, video.height);
options.onFrame(canvas);
} catch (e) {
// TODO
}
}, Math.round(1000 / options.fps));
}
function stopCapture() {
pauseCapture();
if (video.mozSrcObject !== undefined) {
video.mozSrcObject = null;
} else {
video.src = "";
}
}
function pauseCapture() {
if (renderTimer) clearInterval(renderTimer);
video.pause();
}
return {
init: function(captureOptions) {
var doNothing = function(){};
options = captureOptions || {};
options.fps = options.fps || 30;
options.width = options.width || 640;
options.height = options.height || 480;
options.mirror = options.mirror || false;
options.targetCanvas = options.targetCanvas || null; // TODO: is the element actually a <canvas> ?
options.onSuccess = options.onSuccess || doNothing;
options.onError = options.onError || doNothing;
options.onNotSupported = options.onNotSupported || doNothing;
options.onFrame = options.onFrame || doNothing;
initVideoStream();
},
start: startCapture,
pause: pauseCapture,
stop: stopCapture
};
})();