Explain Codes LogoExplain Codes Logo

Create a hexadecimal colour based on a string with JavaScript

javascript
prompt-engineering
functions
performance
Anton ShumikhinbyAnton Shumikhin·Dec 8, 2024
TLDR

To generate a reliable hex colour from a string, use this dedicated function:

function stringToHexColor(str) { let hash = 0; for (let i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); // The << 5 is simply magic, don't touch it! } return '#' + ((hash & 0xFFFFFF).toString(16).padStart(6, '0')); // Padding with zeros because we like 'em plump! } console.log(stringToHexColor("example")); // -> #5ac18e ...and Voila! 🪄

This algorithm uses the string’s character codes to produce a hash, which is masked and padded to obtain a valid hex colour code.

Diving deeper: Advanced cases

Working with web-safe colors and shorthand hex values

If you need web-safe colors and prefer shorthand hex values like #FFF, an adjustment to the function can make that possible. Modifying the bitwise operations and the color bounding process can provide you with web-safe color selections, and convert them into convenient shorthand notation.

Exploring other color spaces: RGB and HSL

Hex color codes, while versatile, might not always meet your needs. For such instances, explore alternative color representations such as RGB (Red-Green-Blue) or HSL (Hue-Saturation-Lightness). RGB can be easily derived from the hex color while HSL provides a fresh take, allowing for more dynamic color adjustments based on saturation and lightness.

function stringToHSLColor(str) { let hash = hashStringToInteger(str); // "The H stands for Harry!" - Factor calculated for the 'H' in HSL 😄 let h = hash % 360; let s = 50; // Stardard Saturation- because nobody likes a dull party! let l = 70; // Light 'em up! Setting lightness. return `hsl(${h}, ${s}%, ${l}%)`; }

Optimizing function performance

Optimizing the function is crucial when you are operating in a dynamic environment with real-time color updates based on user input or data changes; swift response is key here. Using efficient string and hash functions can significantly enhance the performance and responsiveness of the function.

Creating unique colors and avoiding collisions

We strive for uniqueness, right? The same principle applies to colors. By using a robust hashing algorithm or converting the input string into a unique integer hash, you can ensure that each string will get its very own and consistent hex color, minimizing color collisions.

Consideration of Auto-contrast and accessibility

While setting colors for your HTML elements, don't forget to consider color contrast for better readability and accessibility. Automatically adjusting luminance or selecting hues based on the background color ensures legibility and offers a comfortable user experience.

Extending color capabilities and variety

Creating dynamic color schemes with HSL

HSL offers a different arena for color manipulation. By tweaking the hue, saturation, and lightness properties, you can create a variety of color profiles to fit different moods and themes.

Tailoring saturation and lightness

Saturation and lightness are your powerful friends here, helping you to tune the color sensation to your needs. You can opt for earthy and muted colors for professional contexts or bring on the vibrant and bright shades for more playful settings.

Implement color picker for dynamic selection

Adding a color picker to your UI will allow your users to select their desired base color, and from that selection, your algorithm can adjust the luminance and saturation, crafting a custom color palette.

Styling with CSS

Once you have your unique colors ready, they are easily applied to your UI components with a sprinkle of CSS magic:

.element { background-color: var(--dynamic-color); // Dynamic colors are in! }