-2

I am trying to capture image from webcam into a canvas and I would like to store this image data as an pixel array. How can I store it, please?

this is how I am drawing the picture from webcam to a context:

context = canvas.getcontext('2d');
captureButton.addEventListerner('click', ()=> {
context.drawImage(player, 0, 0, canvas.width. canvas.height);}

player is defined in html as <video id='player' controls autoplay></video>

best regards

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mshz
  • 17
  • 4
  • Does this answer your question? [Capture high resolution video/image html5](https://stackoverflow.com/questions/15849724/capture-high-resolution-video-image-html5) – Eriks Klotins Feb 21 '20 at 11:25

1 Answers1

0

This is something I've already done in my library jsia, so I'll expand it out for you here:

This doesn't work on Stack Exchange because of security restrictions, but you can see it working at https://mellen.github.io/jsiaExamples/barcodeReader

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var vid = document.getElementById('vid');

function setupVideoCallback(videoElement, callbackCapture, callbackError, timeBetweenFrames)
{
  var localMediaStream = null;

  navigator.getUserMedia = ( navigator.getUserMedia ||
                             navigator.webkitGetUserMedia ||
                             navigator.mozGetUserMedia ||
                             navigator.msGetUserMedia );

  var um = navigator.mediaDevices.getUserMedia({video: true}).then(handleVid).catch(vidErr);
  
  if(!um)
  {
    um = navigator.getUserMedia({video: true}, handleVid, vidErr);
  }

  function handleVid(stream)
  {
    videoElement.srcObject = stream;
    localMediaStream = stream;
  }
  
  function vidErr(e)
  {
    callbackError(e)
  }

  function capture()
  {
    if(localMediaStream)
    {
      callbackCapture();
    }
  }

  setInterval(capture, timeBetweenFrames);
}

function drawVideoOnCanvas()
{
  canvas.width = vid.clientWidth;
  canvas.height = vid.clientHeight;
      
  ctx.drawImage(vid, 0, 0);
}

setupVideoCallback(vid, drawVideoOnCanvas, e => console.log(e), 10);
<canvas id="canvas"></canvas>
<video autoplay style="visibility:hidden" id="vid"></video>
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90