JavaScript 计算更亮的颜色 [英] JavaScript Calculate brighter colour

查看:29
本文介绍了JavaScript 计算更亮的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JS 中有一个颜色值作为字符串

I have a colour value in JS as a string

#ff0000

我将如何以编程方式计算这种颜色的更亮/更亮版本,例如 #ff4848,并能够通过百分比计算亮度,例如

How would I go about programatically calculating a brighter/lighter version of this colour, for example #ff4848, and be able to calculate the brightness via a percentage, e.g.

increase_brightness('#ff0000', 50); // would make it 50% brighter

推荐答案

function increase_brightness(hex, percent){
    // strip the leading # if it's there
    hex = hex.replace(/^s*#|s*$/g, '');

    // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
    if(hex.length == 3){
        hex = hex.replace(/(.)/g, '$1$1');
    }

    var r = parseInt(hex.substr(0, 2), 16),
        g = parseInt(hex.substr(2, 2), 16),
        b = parseInt(hex.substr(4, 2), 16);

    return '#' +
       ((0|(1<<8) + r + (256 - r) * percent / 100).toString(16)).substr(1) +
       ((0|(1<<8) + g + (256 - g) * percent / 100).toString(16)).substr(1) +
       ((0|(1<<8) + b + (256 - b) * percent / 100).toString(16)).substr(1);
}

/**
 * ('#000000', 50) --> #808080
 * ('#EEEEEE', 25) --> #F2F2F2
 * ('EEE     , 25) --> #F2F2F2
 **/

这篇关于JavaScript 计算更亮的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆