Transform a string into a unique image.
Liedenticon is a refinement of Identicon that separates image generation into two classes — one for SVGs and one for PNGs — with flexible hex color support and percentage padding. Ships as plain ES modules with zero dependencies; works in Node and the browser.
Import directly from this site:
import {
SVG,
PNG,
} from "https://johnhenry.github.io/lib/js/liedenticon/1.0.0/index.mjs";
or install via npm (npm install liedenticon) and import by name:
import { SVG, PNG } from "liedenticon";
By default the SVG class generates an svg string to be embedded in a document.
console.log(String(new SVG("efb8c90a13f7a1fdc4910"))); // "<svg ..."
Passing a truthy parameter to the toString method creates a string that
can be used directly as the source attribute of an image.
new SVG("efb8c90a13f7a1fdc4910").toString(true); // "data:image/svg+xml;utf8,<svg ..."
Passing a second truthy parameter returns the base64-encoded string.
new SVG("efb8c90a13f7a1fdc4910").toString(true, true); // "data:image/svg+xml;base64,..."
The PNG class generates a base64 string, by default with a data-URI preamble attached — usable directly as an image source.
const img = document.createElement("img");
img.src = new PNG("efb8c90a13f7a1fdc4910");
document.body.appendChild(img);
Passing a falsy parameter to toString drops the preamble.
new PNG("efb8c90a13f7a1fdc4910").toString(false); // raw base64
Both classes take an options object as a second argument:
new SVG("efb8c90a13f7a1fdc4910", {
size: 128, // width/height in pixels (default 64)
padding: "20%", // padding — number, numeric string, or percentage
saturation: 0.75, // derived-foreground saturation
brightness: 0.5, // derived-foreground brightness
background: [0, 0, 0, 0], // background color (default transparent)
foreground: "#36c", // foreground color (default derived from hash)
});
In addition to [r, g, b] / [r, g, b, a] arrays, colors may be given as
1, 2, 3, 4, 6, or 8 digit hex codes (with or without a leading #); 2, 4,
and 8 digit codes carry an alpha channel.
Liedenticon replaces Identicon's "margin" option with "padding", matching
the CSS definition most
web developers expect; percentage strings such as "20%" are supported.
Both classes inherit from an internal Graphic class. Support other
formats by extending it and implementing renderImage and toString:
import Graphic from "liedenticon/graphic";
class NewFormat extends Graphic {
renderImage(hash, size, padding, background, foreground) {
// ...
}
toString() {
// ...
}
}
See this module's test suite, liedenticon.jest.test.mjs, for working examples, and the 0.0.4 demo for an in-browser demonstration.