css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container">
  <div class="column">
    <video id="SourceVideo"></video>
  </div>
  <div class="column">
    <div class="canvas">
       <canvas id="Canvas" class="video"></canvas>
    </div>
  </div>
</div>

<button id="StartButton">Start</button>
From: <input type="color" id="FromColor" value="#21204B">
To: <input type="color" id="ToColor" value="#F4CFFD">
            
          
!
            
              .container {
  display: flex;
  width: 400px;
  
  .column {
    max-width: 100%;
    flex: 0 0 400px;
  }
  
  video, canvas {
    max-width: 100%;
    background: #ccc;
  }
}

.video-container {
  width: 400px;
}
            
          
!
            
              var startButton;
var fromColor;
var toColor;
var canvas;
var context;
var video;
var gradients = {};

function init() {
  startButton = document.getElementById('StartButton');
  fromColor = document.getElementById('FromColor');
  toColor = document.getElementById('ToColor');
  canvas = document.getElementById('Canvas');
  context = canvas.getContext('2d');
  video = document.getElementById('SourceVideo');

  if (video.readyState >= 3) {
    readyToPlay();
  } else {
    video.addEventListener('canplay', readyToPlay);
  }
  
  startButton.addEventListener('click', function () {
    startCamera();
  });
}

function readyToPlay() {
  // Set the canvas the same width and height of the video
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  // Play video
  video.play();
  drawFrame(video);
}

function initCamera(stream) {
    video.src = window.URL.createObjectURL(stream);
}

function startCamera() {
  if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
      .then(initCamera)
      .catch(console.error);
  }
}

function drawFrame(video) {
  context.drawImage(video, 0, 0);
  
  var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  applyDuotone(imageData.data, fromColor.value, toColor.value);
  context.putImageData(imageData, 0, 0);
  
  setTimeout(function () {
    drawFrame(video);
  }, 10);
}

function applyDuotone(data, color1, color2) {
  var gradientColors = createGradient(color1, color2);

  applyGrayscale(data);
  for (var i = 0; i < data.length; i += 4) {
    data[i] = gradientColors[data[i]].r;
    data[i+1] = gradientColors[data[i+1]].g;
    data[i+2] = gradientColors[data[i+2]].b;
    data[i+3] = 255;
  }
}

function applyGrayscale(data) {
  for (var i = 0; i < data.length; i+=4) {
    var r = data[i];
    var g = data[i+1];
    var b = data[i+2];
    var gray = (r+g+b)/3;
    
    data[i] = data[i+1] = data[i+2] = gray;
  }
}

function createGradient(fromHex, toHex) {
  if (gradients[fromHex + toHex]) {
    return gradients[fromHex + toHex];
  }
  
  var gradient = [];
  var maxValue = 255;
  var from = getRGBColor(fromHex);
  var to = getRGBColor(toHex);

  for (var i = 0; i <= maxValue; i++) {
    var intensityB = i;
    var intensityA = maxValue - intensityB;
    
    gradient[i] = {
      r: (intensityA*from.r + intensityB*to.r) / maxValue,
      g: (intensityA*from.g + intensityB*to.g) / maxValue,
      b: (intensityA*from.b + intensityB*to.b) / maxValue
    };
  }
  
  gradients[fromHex + toHex] = gradient;

  return gradient;
}

function getRGBColor(hex)
{
  var colorValue;

  if (hex[0] === '#') {
    hex = hex.substr(1);
  }
  
  colorValue = parseInt(hex, 16);
  
  return {
    r: colorValue >> 16,
    g: (colorValue >> 8) & 255,
    b: colorValue & 255
  }
}

window.addEventListener('load', init);

// MediaDevices polyfill
(function() {

	var promisifiedOldGUM = function(constraints, successCallback, errorCallback) {

		// First get ahold of getUserMedia, if present
		var getUserMedia = (navigator.getUserMedia ||
				navigator.webkitGetUserMedia ||
				navigator.mozGetUserMedia ||
				navigator.msGetUserMedia);

		// Some browsers just don't implement it - return a rejected promise with an error
		// to keep a consistent interface
		if(!getUserMedia) {
			return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
		}

		// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
		return new Promise(function(successCallback, errorCallback) {
			getUserMedia.call(navigator, constraints, successCallback, errorCallback);
		});
		
	}

	// Older browsers might not implement mediaDevices at all, so we set an empty object first
	if(navigator.mediaDevices === undefined) {
		navigator.mediaDevices = {};
	}

	// Some browsers partially implement mediaDevices. We can't just assign an object
	// with getUserMedia as it would overwrite existing properties.
	// Here, we will just add the getUserMedia property if it's missing.
	if(navigator.mediaDevices.getUserMedia === undefined) {
		navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
	}
	
})();
// End polyfill --------
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console