JavaScript30 - Day 19

By Camilla Krag Jensen naxoc |

Day 19 of #javascript30 is messing around with the webcam for a photo booth and doing cool effects by manipulating the RGB channels.

Webcam with JavaScript

Is so easy! You call getUserMedia() on the mediaDevices singleton to get a promise. Like this for instance:

const video = document.querySelector('.player');
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  .then(localMediaStream => {
    console.log(localMediaStream);
    video.src = window.URL.createObjectURL(localMediaStream);
    video.play();
  })
  .catch(err => {
    console.error('Ut oh', err);
  });

I had no idea that image manipulation was as simple as it is. There are 3 color channels in an RGB[A] image plus an alpha channel. I'm probably using the wrong words for these things, because I know very little about it. But go look at Pixel manipulation with canvas if you want to know more about how to change colors and make cool effects on images with JavaScript.

toDataURL()

Calling toDataURL() on a canvas element will give you the canvas content as a data url that you can either display or let the user download (or both!). Use the download attribute on the <a> tag to allow download.

const data = canvas.toDataURL('image/jpeg');
const link = document.createElement('a');
link.href = data;
link.setAttribute('download', 'smiling-face');
// Use the data for the image.
link.innerHTML = `<img src="${data}" alt="Smiling face" />`;

This was so cool. Interacting with an amazing piece of software like the browser is is so much fun. It's amazing what you can do with so little code! I really liked the CSS from the assignment that made my little webcam snaps look like polaroids:

Photo bootd