Spice Up Your Website with These Color-Related Functions

darkterminal avatar
GitHub Account@darkterminal
LanguageJAVASCRIPT
Published At2023-04-21 05:05:44

The Back Story about your Javascript Metaphor

Colors are a crucial aspect of web design, and they play a significant role in attracting visitors and conveying emotions. In this article, we will introduce you to a set of color-related functions that can help you add more personality to your website.

The javascript Story!

Are you looking to add some more color to your website? Do you want to create a more visually appealing site that captures your audience's attention? Look no further than these five color-related functions. Btw, i use this function for labeling data in my Metaphor Story - React Table

image

Converting Hex Color Codes to RGB Values

1/**
2 * Converts a hex color code to an object containing its RGB values.
3 *
4 * @param {string} hex - The hex color code to convert.
5 * @returns {Object} An object containing the red, green, and blue values of the hex color code.
6 */
7function hexToRgb(hex) {
8    const r = parseInt(hex.slice(1, 3), 16);
9    const g = parseInt(hex.slice(3, 5), 16);
10    const b = parseInt(hex.slice(5, 7), 16);
11    return { r, g, b };
12}

If you're not familiar with the concept, a hex color code is a six-digit code that represents a color in hexadecimal format. However, sometimes you may need to convert this code to RGB values to achieve a specific effect or use in some calculations. With our hexToRgb function, you can do just that. Simply input your hex color code, and the function will return an object with the red, green, and blue values of that color.

Converting RGB Color Values to Hex Color Codes

1/**
2 * Converts RGB color values to hex color code.
3 *
4 * @param {number} r - The red color value (0-255).
5 * @param {number} g - The green color value (0-255).
6 * @param {number} b - The blue color value (0-255).
7 * @returns {string} The hex color code.
8 */
9function rgbToHex(r, g, b) {
10    const hexR = r.toString(16).padStart(2, '0');
11    const hexG = g.toString(16).padStart(2, '0');
12    const hexB = b.toString(16).padStart(2, '0');
13    return `#${hexR}${hexG}${hexB}`;
14}

On the flip side, if you have an RGB color value, you may need to convert it to a hex color code. This is where our rgbToHex function comes in handy. Input the red, green, and blue values, and the function will return the hex color code for that color.

Generating Shades of a Color

1/**
2 * Generate color shades
3 * @param {string} hex color string
4 * @param {number} numShades the number of color shades
5 * @param {null|number} onlyShade the number is accourding from numShades with index start from 0
6 * @returns {array|string} colors array or string
7 */
8export function generateShades(hex, numShades, onlyShade = null) {
9    // Convert the hex color to RGB
10    const rgb = hexToRgb(hex);
11    // Initialize the shades array
12    const shades = [];
13    // Determine the color step
14    const step = Math.round(255 / (numShades - 1));
15    // Generate the shades of the color
16    for (let i = 0; i < numShades; i++) {
17        const r = Math.max(Math.min(rgb.r + i * step, 255), 0);
18        const g = Math.max(Math.min(rgb.g + i * step, 255), 0);
19        const b = Math.max(Math.min(rgb.b + i * step, 255), 0);
20        // Convert the RGB color back to hex
21        const shade = rgbToHex(r, g, b);
22        shades.push(shade);
23    }
24    return onlyShade !== null ? shades[onlyShade] : shades;
25}

Looking to add more depth to your website by creating a gradient effect? Our generateShades function can help you create multiple shades of a color, giving your site a more dynamic appearance. Simply input the hex code of the color you want to use, and the number of shades you want to create. You can even generate only one specific shade by inputting the index of the shade you want.

Generating Hex Color Codes from Strings

1/**
2 * Generates a hex color code from a string using a simple hash function.
3 * @param {string} anyString - The input string to generate the hex color code from.
4 * @returns {string} The generated hex color code.
5 */
6export function generateHexColor(anyString) {
7    // Use a simple hash function to generate a number from the anyString
8    let hash = 0;
9    for (let i = 0; i < anyString.length; i++) {
10        hash = anyString.charCodeAt(i) + ((hash << 5) - hash);
11    }
12
13    // Generate a 24-bit color from the hash
14    let color = (hash & 0x00FFFFFF).toString(16).toUpperCase();
15
16    // Pad the color code with zeros if necessary
17    while (color.length < 6) {
18        color = "0" + color;
19    }
20
21    // Prepend a hash symbol to the color code
22    return "#" + color;
23}

Sometimes you may want to generate a color based on a specific string, such as a user's name or username. With our generateHexColor function, you can do just that. Simply input any string, and the function will use a simple hash function to generate a 24-bit color from that string. The result is a unique hex color code that you can use to add more personality to your website.

Calculating the Opposite Color of a Hexadecimal Color

1/**
2 * Calculates the opposite color of the given hexadecimal color.
3 *
4 * @param {string} hexColor - The hexadecimal color to calculate the opposite of.
5 * @returns {string} The opposite color in hexadecimal format.
6 */
7export function getOppositeColor(hexColor) {
8    // Remove the "#" character if present
9    hexColor = hexColor.replace("#", "");
10
11    // Convert the hex color to RGB
12    const red = parseInt(hexColor.substr(0, 2), 16);
13    const green = parseInt(hexColor.substr(2, 2), 16);
14    const blue = parseInt(hexColor.substr(4, 2), 16);
15
16    // Calculate the opposite color
17    const oppositeRed = 255 - red;
18    const oppositeGreen = 255 - green;
19    const oppositeBlue = 255 - blue;
20
21    // Convert the opposite color to hex
22    const oppositeHex = "#" +
23        oppositeRed.toString(16).padStart(2, "0") +
24        oppositeGreen.toString(16).padStart(2, "0") +
25        oppositeBlue.toString(16).padStart(2, "0");
26
27    return oppositeHex;
28}

Finally, if you're looking to create more contrast on your website, our getOppositeColor function can help you achieve just that. Input a hex color code, and the function will return the opposite color in hexadecimal format. This can help you create a more visually appealing site that stands out to your visitors.

In conclusion, adding more color to your website doesn't have to be difficult or time-consuming. With these five functions, you can easily create unique colors and gradients that give your site more personality and appeal.

That's it! Thank for reading my Metaphor Story...

A Javascript demo/repos link

None

PayPal Link for Donation (Javascript Storyteller)

https://www.paypal.me/lazarusalhambra

Share This Story