Created
June 16, 2021 02:34
-
-
Save susanlangenes/e7ca007fd2d5e8b1b0811a3367a6e3dc to your computer and use it in GitHub Desktop.
pixelated-face.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const faceDetector = new window.FaceDetector(); | |
const video = document.querySelector('video.webcam'); | |
const canvas = document.querySelector('canvas.video'); | |
const ctx = canvas.getContext('2d'); | |
const faceCanvas = document.querySelector('canvas.face'); | |
const faceCtx = faceCanvas.getContext('2d'); | |
const SIZE = 10; | |
const SCALE = 1.2; | |
//write a function that will populate the user's video | |
async function populateVideo() { | |
const stream = await navigator.mediaDevices.getUserMedia({ | |
video: { width: 1280, height: 720 }, | |
}); | |
video.srcObject = stream; | |
await video.play(); | |
//size canvas to match actual video | |
canvas.width = video.videoWidth; | |
canvas.height = video.videoHeight; | |
faceCanvas.width = video.videoWidth; | |
faceCanvas.width = video.videoWidth; | |
} | |
async function detect() { | |
const faces = await faceDetector.detect(video); | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
faces.forEach(drawFace); | |
faces.forEach(censor); | |
requestAnimationFrame(detect); | |
} | |
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, | |
face.x, | |
face.y, | |
face.width, | |
face.height, | |
// 4 draw args | |
face.x, | |
face.y, | |
SIZE, | |
SIZE | |
); | |
const width = face.width * SCALE; | |
const height = face.height * SCALE; | |
// take that face back out and draw it back at normal size | |
faceCtx.drawImage( | |
faceCanvas, //src | |
face.x, | |
face.y, | |
SIZE, | |
SIZE, | |
//drawing args | |
face.x - (width - face.width) / 2, | |
face.y - (height - face.height) / 2, | |
width, | |
height | |
); | |
} | |
function drawFace(face) { | |
const { width, height, top, left } = face.boundingBox; | |
ctx.strokeStyle = '#ffc600'; | |
ctx.lineWidth = 1; | |
ctx.strokeRect(left, top, width, height); | |
ctx.stroke(); | |
} | |
populateVideo().then(detect); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment