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 – https://www.purplesquirrels.com.au/2013/08/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:


1
2
3
4
5
6
7
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:


1
2
3
4
5
6
7
8
9
10
11
// 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

Getting WebSockets working with Node, Socket.io and Elastic Beanstalk

This is something that took me nearly a year to get working. Not full time obviously, but every now and then I would make another attempt at getting it working after the trauma of the previous attempt had faded. None of the examples that people had provided worked for me, and some were out dated and no longer applied. And of course the AWS documentation provided no help whatsoever.

I decided to share my configuration in the hope that it will help someone else. Here is a list of the technologies I am using:

  • The app is a NodeJS app running on 6.11.X, soon to be 8.4.X
  • Using the Express server framework and Socket.io for WebSockets
  • Using AWS Elastic Beanstalk
  • Nginx with reverse proxy to NodeJS
  • Using the newer Application Load Balancer
  • HTTPS is enabled
  • Front and back end running on same domain

READ MORE

Sorting strings with JS (properly)

It seems like such a basic task – how to sort a list of strings alphabetically.

The easiest way, and what you’d probably stumble across first, is a simple sort function:

1
arr.sort();

Or using the sort() function and passing a compare function:

1
arr.sort((a, b) => a > b);

Or sorting on object property:

1
2
3
4
5
arr.sort(function(a, b){
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
})

This is the most common answer when searching Google/Stack Overflow on how to sort an array. It works for simple strings, however you can quickly run into issues when numbers get involved where 10 can appear before 2 etc. And then there are special characters and languages other than English – what determines where they appear in an alphabetical list?

It’s not easy to find this answer – is it assumed knowledge? I quickly discovered a bunch of highly complicated sorting functions that people had glued together on Stack Overflow. But I thought surely there is a simpler way for such a basic and common task.
READ MORE

Using ES6 template strings to generate unique strings

The following technique is something that I found template strings in ES6 to be quite useful for. I needed to generate XML chunks (as a string) where each node had a unique ID every time the XML was generated.

Most examples of template strings I see around the web just use simple variables inside template strings. I found that you can also use functions that return a value, making the string even more dynamic.

I ended up writing a function that creates the string and inserts unique IDs in specific locations every time the function is called:

1
2
3
4
5
6
7
8
9
const generateID = () => {
  // ... some code to generate and return an ID
}

const getStringTemplate = () => {
  return `<element uid="${generateID()}">
            <child uid="${generateID()}"></child>
          </element>`
}

You can place ${generateID()} any number of times in the template string and in each location a unique ID will be inserted.

Now I can call getStringTemplate() and get a unique chunk of XML every time.

Using Cardboard Camera and A-Frame to create a simple WebVR scene

I have been playing around with VR a bit lately after getting a new Android phone (Nexus 6P), and I thought I’d share a simple experiment I did using Google’s Cardboard Camera app, and the WebVR library A-Frame.

The result of this will be a simple WebVR scene that displays the photo captured from Cardboard Camera in a scene that you can look around.
READ MORE

Paint stencilling with HTML5 canvas

I have recently been playing around with re-writing my Spray paint stencils in Flash using JavaScript and HTML5’s canvas element. One thing I discovered is that since SVGs are natively supported in browsers I can have stencils scaled to any size and remain crisp, unlike the Flash version which used transparent PNGs.

I have implemented stencils, including having a muck layer, and stickers – graphics that you can place and cut out through stencils. When I first started playing around I was writing it all plain JavaScript, but eventually I converted everything over to TypeScript which allowed me to easily separate everything out into their own classes with event listening/dispatching capabilities. Almost mimicking the way things were written in AS3.

Below is a video of the early prototype, I will provide a live demo when it is more ready for public use.

Automatic typography substitution

After reading the series of Death to Typewriters articles on Meduim, I decided to have a go at implementing their automatic character substition rules in JavaScript. Following the guide provided at Death to Typewriters: Automatic replacement and clean-up, I created a simple function that can be called as you type, or when text is pasted, into a text area. Certain character combinations and locations are looked for and replaced with other characters such as correct quotes, arrows and ellipsis. I have put the code up on GitHub with a little bit of documentation.

READ MORE

Recreating the Apple Watch UI using a hexagonal grid

Building on the hexagonal grid from earlier, I have added a little JavaScript and have created an effect similar to the Apple Watch home screen UI.

Below is a video of it in action, I am using IE11 (metro version) on a Surface Pro 2 which I found to be the most performant for this effect. Chrome was janky as hell, and Safari on the iPad doesn’t like to do things while scrolling.
READ MORE

Triggering a ‘finish’ event on an external video with Storyline HTML5

If you have at some point needed to use Articulate Storyline – you have probably come to a point where you want to murder everyone around you (not literally of course!) due to its ridiculous, quirky limitations. More often than not I find myself hacking the published code to make things works how I want.

One of the big limitations in Storyline is video – if you want to trigger something when the video starts or finished you must use the built in player. But the built in player cannot load videos from an external site (such as a streaming server – a common requirement) so you are left with using the ‘video embed code’ option, which doesn’t seem to allow custom embed codes – all I could get to work was YouTube and Vimeo. And even if you can get this to work you can’t add triggers to it for when the video ends.

I found a little hack which uses the Web Object and a custom video player in a HTML page. You can listen for the video complete event in the custom player then change a variable in the Storyline player. Then in Storyline add a trigger for when that particular variable changes, which will be when the video finishes.

Here’s how to do it.
READ MORE