Recipe 18.5

Applying Video Filters

Demo

Filter

Code

JavaScript
const preview = document.querySelector('#preview');
const photo = document.querySelector('#photo');
const canvas = document.querySelector('#canvas');

async function startCamera() {
  const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });

  // Hook up the video element to the stream.
  preview.srcObject = stream;
  preview.play();

  // Resize the canvas based on the device pixel density
  // This helps prevent a blurred or pixellated image.
  canvas.width = canvas.width * window.devicePixelRatio;
  canvas.height = canvas.height * window.devicePixelRatio;
  const context = canvas.getContext('2d');

  // Target frame rate of 30 FPS - draw each frame to the canvas
  setInterval(() => {
    context.drawImage(preview, 0, 0, canvas.width, canvas.height);
  }, 30 / 1000);
}

document.querySelector('#filterNone').addEventListener('click', event => {
  canvas.style.filter = 'none';
});

document.querySelector('#filterGrayscale').addEventListener('click', event => {
    canvas.style.filter = 'grayscale(100%)';
});

document.querySelector('#filterHueRotate').addEventListener('click', event => {
  canvas.style.filter = 'hue-rotate(90deg)';
});

startCamera();
HTML
<style>
  #canvas {
    width: 640px;
    height: 480px;
  }
</style>

<div class="d-flex flex-column align-items-center">
  <canvas id="canvas"></canvas>
  <video id="preview" class="d-none"></video>
</div>

<fieldset>
  <legend>Filter</legend>
  <div class="d-flex">
    <div class="form-check m-2">
      <input class="form-check-input" type="radio" name="filter" id="filterNone" checked>
      <label class="form-check-label" for="filterNone">
        No filter
      </label>
    </div>
    <div class="form-check m-2">
      <input class="form-check-input" type="radio" name="filter" id="filterGrayscale">
      <label class="form-check-label" for="filterGrayscale">
        Grayscale
      </label>
    </div>
    <div class="form-check m-2">
      <input class="form-check-input" type="radio" name="filter" id="filterHueRotate">
      <label class="form-check-label" for="filterHueRotate">
        Hue rotate
      </label>
    </div>
  </div>
</fieldset>
Web API Cookbook
Joe Attardi