Skip to content

Instantly share code, notes, and snippets.

@arifd
Created January 13, 2020 19:16
Show Gist options
  • Save arifd/f7a7021c93781dc5141acbc345bed193 to your computer and use it in GitHub Desktop.
Save arifd/f7a7021c93781dc5141acbc345bed193 to your computer and use it in GitHub Desktop.
Get webcam into WebGL
// In INITIALISATION:
// create webcam stream
let video = document.createElement('video');
video.width = 320;
video.height = 240;
video.autoplay = true;
let constraints = {video: true};
navigator.mediaDevices.getUserMedia(constraints).then(stream => video.srcObject = stream);
// IN YOUR RENDER LOOP
// setup a canvas that will receive the webcam images
let webcamCanvas = document.createElement('canvas');
webcamCanvas.width = video.width;
webcamCanvas.height = video.height;
webcamCanvas.getContext('2d').drawImage(video, 0, 0, webcamCanvas.width, webcamCanvas.height);
// make an image from the canvas
let webcamImage = new Image();
webcamImage.src = webcamCanvas.toDataURL();
webcamImage.onload = () =>
{
// use the new image as a texture
let webcamTexture = gl.createTexture();
// send to GPU
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, webcamTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webcamImage);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment