Getting headless Chrome to run on AWS Lambda Node

Today I needed to update a couple Lambda functions from the Node 8 runtime to use the Node 10.x runtime. These functions required headless Chrome because they are used to take screenshots. Unfortunately, moving from the Node 8 runtime to 10x runtime is not a simple as it sounds, because AWS have decided to change the Linux environment which now excludes some files that Chromium requires to run.

As a reminder to myself, and for anyone else who might find it useful, I thought I’d document my setup here in a blog post. This post will assume you have the Serverless CLI set up and successfully deploying to AWS.

READ MORE

Saving a Canvas element as an image

Here’s a little tip to allow your users download the contents of a canvas element as an image, without the need for a server. We can do this by using an Anchor tag with a download attribute.

Start with creating <canvas> and <a> tags:

<canvas id="mycanvas"></canvas>
<a href="#" download="MyImage.png" id="downloadlink">Save canvas</a>

The <a> tag’s download attribute can be set to a file name that will be used when saving the file. If no value is specified, it will just be called Download.png.

READ MORE

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.

Inspiring Inspiration #16

A collection of cool video, motion graphics and interface design.

READ MORE