This function allows you to programmatically lighten or darken a hex color by a specific amount. Simply pass in a string like "3F6D2A" for the color and an integer amt for the amount to lighten or darken. To darken, pass in a negative number (e.g., -20).
function LightenDarkenColor(col, amt) {
col = parseInt(col, 16);
return (((col & 0x0000FF) amt) | ((((col >> 8) & 0x00FF) amt) > 16) amt) Other versions
Faster and smaller version:
function LightenDarkenColor(col, amt) {
var num = parseInt(col, 16);
var r = (num >> 16) amt;
var b = ((num >> 8) & 0x00FF) amt;
var g = (num & 0x0000FF) amt;
var newColor = g | (b Handle colors with or without the # prefix:
function LightenDarkenColor(col, amt) {
var usePound = false;
if ( col[0] == "#" ) {
col = col.slice(1);
usePound = true;
}
var num = parseInt(col, 16);
var r = (num >> 16) amt;
if ( r > 255 ) r = 255;
else if (r > 8) & 0x00FF) amt;
if ( b > 255 ) b = 255;
else if (b 255 ) g = 255;
else if ( g Usage
To use the function, simply pass in the hex color string you want to lighten or darken, and the amount you want to adjust it by. For example, the following code lightens the color "3F6D2A" by 40:
const lightenedColor = LightenDarkenColor("3F6D2A", 40);
console.log(`Lightened Color: ${lightenedColor}`); // Output: 7FADEE
Performance
The performance of this function is optimized for speed and size. It uses bitwise operations to manipulate the color values, which makes it extremely fast. The function is also very small, making it ideal for use in small applications.
Features
- Lightens or darkens a hex color by a specified amount
- Handles colors with or without the # prefix
- Adjusts for improper color values
- Returns a hex string representation of the new color
Limitations
- The function does not convert the color to HSL to properly lighten or darken the color. Therefore, the results may differ from functions that use HSL.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3