将HSL颜色字符串转换为具有每个颜色值的对象
思路:
- 使用String.prototype.match()获取一个包含3个字符串和数值的数组;
- 将Array.prototype.map()与Number结合使用,将它们转换为数值数组;
- 使用数组分解将值存储到命名变量中,并从中创建适当的对象。
代码实现:
- const toHSLObject = (hslStr) => {
- const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
- return { hue, saturation, lightness };
- }
- //测试
- console.log(toHSLObject('hsl(50, 10%, 10%)')); // { hue: 50, saturation: 10, lightness: 10 }
根据以上思路,可将RGB、RGBA、HSLA进行同样的处理,如下:
拓展一:将RGB颜色字符串转换为具有每个颜色值的对象
代码实现:
- const toRGBObject = ( rgbStr ) => {
- const [red, green, blue] = rgbStr.match(/\d+/g).map(Number);
- return {red, green, blue};
- }
- console.log(toRGBObject('rgb(128,0,128)')); // { red: 128, green: 0, blue: 128 }
拓展二:将RGBA颜色字符串转换为具有每个颜色值的对象
代码实现:
- const toRGBAObject = (rgbaStr) => {
- let [red, green, blue, alpha] = rgbaStr.match(/\d+(\.\d+)?/g).map(Number);
- return {red, green, blue, alpha};
- }
- console.log(toRGBAObject('rgba(128,0,128, 0.5')); // { red: 128, green: 0, blue: 128, alpha: 0.5 }
拓展三:将HSLA颜色字符串转换为具有每个颜色值的对象
代码实现:
- const toRGBAObject = (hslaStr) => {
- const [hue, saturation, lightness, alpha] = hslaStr.match(/\d+(\.\d+)?/g).map(Number);
- return { hue, saturation, lightness, alpha};
- }
- console.log(toRGBAObject('hsla(128,0,128, 0.5')); // { hue: 128, saturation: 0, lightness: 128, alpha: 0.5 }