Posts Tagged ‘CodePens’

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.