-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
122 lines (92 loc) · 2.73 KB
/
main.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
(function (doc, nav) {
"use strict";
var video, width, height, context;
var myImages = ['front_cam_2.png','front_left_cam_2.png',
'side_left_cam_2.png','back_left_cam_2.png','back_cam_2.png',
'back_right_cam_2.png','side_right_cam_2.png','front_right_cam_2.png'];
var img_index = 0;
function initialize() {
// The source video.
video = doc.getElementById("v");
width = video.width;
height = video.height;
// The target canvas.
var canvas = doc.getElementById("c");
context = canvas.getContext("2d");
// Get the webcam's stream.
nav.getUserMedia({video: true}, startStream, function () {});
}
function startStream(stream) {
video.src = URL.createObjectURL(stream);
video.play();
// Ready! Let's start drawing.
requestAnimationFrame(draw);
}
function draw() {
var frame = readFrame();
if (frame) {
replaceGreen(frame.data);
context.putImageData(frame, 0, 0);
}
// Wait for the next frame.
requestAnimationFrame(draw);
}
function readFrame() {
try {
context.drawImage(video, 0, 0, width, height);
} catch (e) {
// The video may not be ready, yet.
return null;
}
return context.getImageData(0, 0, width, height);
}
function replaceGreen(data) {
var len = data.length;
for (var i = 0, j = 0; j < len; i++, j += 4) {
// Convert from RGB to HSL...
var hsl = rgb2hsl(data[j], data[j + 1], data[j + 2]);
var h = hsl[0], s = hsl[1], l = hsl[2];
// ... and check if we have a somewhat green pixel.
if (h >= 90 && h <= 160 && s >= 25 && s <= 90 && l >= 20 && l <= 75) {
data[j + 3] = 0;
}
}
}
function rgb2hsl(r, g, b) {
r /= 255; g /= 255; b /= 255;
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h, s, l;
if (max == min) {
h = 0;
} else if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else if (b == max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max == min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
}
function change_image() {
//here "this" will point to button, the element which is clicked ie event occurred.
//but we need image, so get it by using below statement
var img = document.getElementById("headimg");
img_index = ++img_index % 8; //replace 2 with number of images
img.src = myImages[img_index];
}
addEventListener("DOMContentLoaded", initialize);
})(document, navigator);