Skip to content

Commit a00e71e

Browse files
author
Charlie
committed
day 19
1 parent 8805389 commit a00e71e

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

19 - Webcam Fun/scripts.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,62 @@ const canvas = document.querySelector('.photo');
33
const ctx = canvas.getContext('2d');
44
const strip = document.querySelector('.strip');
55
const snap = document.querySelector('.snap');
6+
7+
function getVideo() {
8+
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
9+
.then(localMediaStream => {
10+
video.src = window.URL.createObjectURL(localMediaStream);
11+
video.play();
12+
})
13+
.catch(err => console.log('fuck it!'));
14+
}
15+
16+
function paintToCanvas() {
17+
const { videoHeight: height, videoWidth: width} = video;
18+
canvas.width = width;
19+
canvas.height = height;
20+
return setInterval(() => {
21+
ctx.drawImage(video, 0, 0, width, height);
22+
let pixels = ctx.getImageData(0, 0, width, height);
23+
// pixels = redEffect(pixels);
24+
pixels = rgbSplit(pixels);
25+
ctx.putImageData(pixels, 0, 0);
26+
27+
}, 16);
28+
}
29+
30+
function takePhoto() {
31+
// play a sound
32+
snap.currentTime = 0;
33+
snap.play();
34+
35+
// take data out of the canvas
36+
const data = canvas.toDataURL('image/jpeg');
37+
const link = document.createElement('a');
38+
link.href = data;
39+
link.setAttribute('download', 'handsome');
40+
link.innerHTML = `<img src="${data}"/>`;
41+
strip.insertBefore(link, strip.firstChild);
42+
}
43+
44+
function redEffect(pixels) {
45+
for (let i = 0; i < pixels.data.length; i += 4) {
46+
pixels.data[i + 0] = pixels.data[i + 0] + 100;
47+
pixels.data[i + 1] = pixels.data[i + 1] - 50;
48+
pixels.data[i + 2] = pixels.data[i + 2] * 0.5;
49+
}
50+
return pixels;
51+
}
52+
53+
function rgbSplit(pixels) {
54+
for (let i = 0; i < pixels.data.length; i += 4) {
55+
pixels.data[i - 150] = pixels.data[i + 0];
56+
pixels.data[i + 100] = pixels.data[i + 1];
57+
pixels.data[i - 150] = pixels.data[i + 2];
58+
}
59+
return pixels;
60+
}
61+
62+
getVideo();
63+
64+
video.addEventListener('canplay', paintToCanvas);

0 commit comments

Comments
 (0)