Archive for February 2016

Generating PNGs in JavaScript

A project I’m working on allows the user to construct their own exterior home design using a set of provided colors, sidings, and trims. Due to technical limitations, I needed to be able to generate a solid-color image on-the-fly in JavaScript to set as a background-image on the element we overlay on the base layer in order to color that section of the home.

A Google search led me to PNGLib by Robert Eisele, which makes creating these images a lot easier. In my case, I needed to convert a hex RGB value into a valid value for background-image, url(...) and all. My code below includes a function imageUrlForColor() accepting three arguments: the hex color string (e.g. "#CE1126"), width, and height and returns the rule value as a string.

BONUS: One of the limitations of the CSS background-blend-mode is that is only works when one of the elements has a background-image, not just a background-color. The technique shown in the example below shows that you can use background-blend-mode on these elements without issue.

See the Pen Generate PNG in JavaScript by Cody Sand (@marpstar) on CodePen.

HTML5 File Uploads with FileAPI by

During a recent hunt for a nice HTML file upload library, I came across FileAPI by In particular, I was looking for a library that was completely framework-independent. jQuery File Upload is a very nice plugin that I’ve used in the past, but for this particular project we needed something not based on jQuery.

What’s particularly cool about this library is that it includes a handful of functions for manipulating images directly. We wanted to generate an image thumbnail before we sent the file to the server for storage. FileAPI can generate a <canvas> thumbnail for you and you can generate a Base64 string of the image by calling .toDataURL() on the <canvas> element.

I took the simple example from the FileAPI docs and tossed them in a CodePen for you to play with. In my example, I filter any selected files to only images, generate a thumbnail for each one, and append it to the document.

Check it out:

See the Pen FileAPI Preview by Cody Sand (@marpstar) on CodePen.

FileAPI also includes functions for transporting the files to your server, capturing images from webcam, drag-and-drop, and a bunch of other stuff you’d expect from an upload library, dependency-free.