Home  >  Article  >  Web Front-end  >  Convert hexadecimal colors in css to rgb format_html/css_WEB-ITnose

Convert hexadecimal colors in css to rgb format_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:56:11907browse

Annotations for the dojo/_base/Color module, source address https://github.com/robinxiong/dojo/blob/master/_base/Color.js


function fromHex(color){        /*         summary:            将css的属性值,转变为rgb格式的对像         "#fff"  -> 0xfff         长度为4, 一个字符占用代表一个属性, 0x10 == 16(2的4次方,即1后面4个0) === 1 0000, 那么一个f 为 1111         占位符为 mask = 1111, 用于占住后四位(&用于保留后四位的值), 其它高位清零         每一次遍历都从后四位开始,所以先获取到 b值,难后移动4位,在获取到 g, 在移动4位,获取到 r         获取b属性:         0000 1111 1111 1111 & 0000 0000 0000 1111 (这里只列举出16位, 正常的是32位)         0000 0000 0000 1111 b保存到变量 c         0000 1111 1111 1111 >> 4, -> 0000 0000 1111 1111         获取g属性         0000 0000 1111 1111 & 0000 0000 0000 1111         0000 0000 0000 1111 获得到g的值,保存到变量 c         在移四位,获取r的值         "ffffff" -> 0xffffff         长度为8,每两个字符代表一个函数 0xff = 1111 1111         每次获取后8位,刚好代表颜色值         */        var t = {},                bits = (color.length == 4) ? 4 : 8,//如果是shorthand, #fff, 那么bits为4位, 每一位代表的个属性, 其它的为8位 每两位代表一个属性 #ffffff00                mask = (1 << bits) - 1; //表示字节占位符, 向左移4位或8位,var a = (1 << 4 ) - 1 -> 10000 - 1,  a.toString(2); // 1111,或者 8位的 1111 1111        color = Number("0x" + color.substr(1)); //#ff0000 转变为16进制0xff0000;        if(isNaN(color)){            return null; // Color        }        ["b", "g", "r"].forEach(function(x){            var c = color & mask;            color >>= bits;            t[x] = bits == 4 ? 17 * c : c; // 0xfff , 一个f应该代表 255, 应该当[0-255],按15等份划分,每一等份间隔 17。 所以获得的值需要乘以17, 才能表示rgb中255的值        });        t.a = 1;        return t;	// Color    }    console.log(fromHex("#00f"))  // {r:0, g: 0, b:255, a:1}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn