-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcamera.js
127 lines (103 loc) · 2.86 KB
/
camera.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
// Camera
// * Use person and face detection to know when people are around, or cats
//
var cameraSource = (function(global) {
var id = 'source-camera',
title = 'Camera',
videoElement = null,
constraints = {
video: true
};
function start(opts) {
if (opts.constraints) {
constraints = opts.constraints;
}
videoElement = opts.videoElement;
showCameraPreview(opts.callback);
}
function showCameraPreview(cb) {
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
if (videoElement) {
videoElement.srcObject = stream;
videoElement.play();
}
if (cb) {
cb(stream);
}
/*
setInterval(function() {
console.log('intval')
videoSnapshot(function(canvas) {
//track.stop();
//addSnapshotToPage(canvas);
// upload photo
canvas.toBlob(function(blob) {
uploadPhoto(blob, function() {
console.log('uploaded!')
});
});
});
}, 2000);
*/
}, function(err) { console.error(err); });
}
// the whole deal
// * videoSnapshot() writes snapshot from video preview to a canvas
// * get the binary data from the snapshot
// * upload the binary data to the server
function snapshot() {
videoSnapshot(function(canvas) {
// upload photo
canvas.toBlob(function(blob) {
uploadPhoto(blob, function() {
console.log('uploaded!')
});
});
});
}
function snapshotToCanvas(cb) {
videoSnapshot(cb);
}
function videoSnapshot(cb) {
var vid = document.querySelector('#vid'),
width = 320,
height = vid.videoHeight / (vid.videoWidth/width),
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
context.drawImage(vid, 0, 0, width, height);
cb(canvas);
}
function addSnapshotToPage(canvas) {
var img = document.createElement('img')
img.src = canvas.toDataURL()
document.body.appendChild(img)
}
function uploadPhoto(fileBlob, callback) {
// Create object for form data
var fd = new FormData();
// 'upl' is the arbitrary string that multer expects to match
// its config on the server end.
fd.append('upl', fileBlob, 'file-' + Date.now() + '.jpg');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://' + window.location.hostname + ':3000/upload');
xhr.onload = function() {
console.log('photo uploadeddddd')
try {
var data = JSON.parse(xhr.responseText).data;
} catch(ex) {
}
}
xhr.send(fd);
console.log('upload: sent');
}
// public
return {
id: id,
title: title,
start: start,
snapshot: snapshot,
snapshotToCanvas: snapshotToCanvas
};
})(this);