html – Save images data of canvas in JavaScript-ThrowExceptions

Exception or error:

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

How to solve:

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

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);
    um = navigator.getUserMedia({video: true}, handleVid, vidErr);

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

  function capture()

  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>

Leave a Reply

Your email address will not be published. Required fields are marked *