-
Notifications
You must be signed in to change notification settings - Fork 0
/
pixelated.face.js
88 lines (77 loc) · 2.48 KB
/
pixelated.face.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
const video = document.querySelector('.webcam');
const canvas = document.querySelector('.video');
const ctx = canvas.getContext('2d');
const faceCanvas = document.querySelector('.face');
const faceCtx = faceCanvas.getContext('2d');
const faceDetector = new window.FaceDetector();
console.log(video, canvas, faceCanvas, faceDetector);
const optionsInputs = document.querySelectorAll('.controls input[type="range"]')
const options = {
SIZE: 10,
SCALE: 1.35,
};
function handleOption(event) {
const { value, name } = event.currentTarget;
options[name] = parseFloat(value);
}
optionsInputs.forEach(input.addEventListener('input', handleOption));
// populate the users video
async function populateVideo() {
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: 1280, height: 720}
});
video.srcObject = stream;
await video.play();
// size the canvases to be the same size as the video
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
faceCanvas.width = video.videoWidth;
faceCanvas.height = video.videoHeight;
};
async function detect() {
const faces = await faceDetector.detect(video);
faces.forEach(drawFace);
faces.forEach(censor);
// ask the browser when the next animation frame is and tell it to run detect for us
requestAnimationFrame(detect);
};
function drawFace(face) {
const { width, height, top, left } = face.boundingBox;
ctx.clearRect(0,0, canvas.width, canvas.height)
ctx.strokeStyle = '#ffc600';
ctx.lineWidth = 2;
ctx.strokeRect(left, top, width, height);
};
function censor({ boundingBox: face }) {
faceCtx.imageSmoothingEnabled = false;
faceCtx.clearRect(0, 0, faceCanvas.width, faceCanvas.height)
// draw the small face
faceCtx.drawImage(
// 5 source args
video, // where does the source come from?
face.x, // where do we start the source pull from ?
face.y, //
face.width,
face.height,
// 4 draw args
options.SIZE, // where should we start drawing the x and y?
options.SIZE,
// take that face back out and draw it back at normal size
);
// draw the small face back on , but scale up
const width = face.width * options.SCALE;
const height = face.height * options.SCALE;
faceCtx.drawImage(
faceCanvas, // source
face.x, // where do we start the source pull from ?
face.y, //
options.SIZE,
options.SIZE,
// drawing args
face.x - (width - face.width) / 2,
face.y - (width - face.height) / 2,
width,
height,
)
}
populateVideo().then(detect);