Capturing an image from your webcam using JavaScript

This post is a bit of an update on one of my popular posts from a few years ago – Webcam to Canvas or data URI with HTML5 and Javascript

I thought I’d do an updated post on how to get an image from webcam using current web APIs. This time we’ll be using the Media Stream API.

To start off, we need to create a couple of HTML elements – a button and an img tag:

<button id="takephoto">Take Photo</button> 
<img id="img" />

For the JavaScript we’ll start by getting the video devices that are available:

let mediaStream;

try {
    mediaStream = await navigator.mediaDevices.getUserMedia({ video: true })
} catch (error) {
    console.error('getUserMedia() error:', error)
}
READ MORE

Processing an array in batches using generators

Generators in JavaScript are something that looks useful on the surface but I have really never found much use for them in my work. However one such use case I came across was processing a large mount of data in an array in batches. I needed to process and push data to a DynamoDB table, but I had to batch it to avoid slamming the table with write operations.

As is turned out, using generators massively simplified the batching code. Here is a simplified example:

// define the generator function that yields
// N items at a time from the provided array
function* getBatch(records, batchsize = 5) {
    while (records.length) {
        yield records.splice(0, batchsize);
    }
}

for (let batch of getBatch(records)) {
    // do something with 5 items at a time
}
READ MORE