Add hexadecimal with alpha color parsing

Closes #1468
This commit is contained in:
PeterLazar 2018-10-05 20:14:20 +02:00 committed by Samuel Asensi
parent a36c1bac75
commit a8f78859cb
2 changed files with 15 additions and 8 deletions

View file

@ -62,14 +62,18 @@ var Color = Base.extend(new function() {
var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),
type = 'rgb',
components;
if (match) {
// Hex
components = [0, 0, 0];
for (var i = 0; i < 3; i++) {
var value = match[i + 1];
components[i] = parseInt(value.length == 1
? value + value : value, 16) / 255;
}
if (/^#[A-Fa-f0-9]+$/.test( string )) {
// HEX / HEX+A
var base = string.replace(/^#/,'');
var size = base.length;
components = base.split( size <= 4 ? /(.)/ : /(..)/ );
components = components.filter(Boolean).map(function(x) {
return parseInt(size <= 4 ? x + x : x, 16) / 255;
});
if ( !components[0] ) components[0] = 0;
if ( !components[1] ) components[1] = 0;
if ( !components[2] ) components[2] = 0;
} else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) {
// RGB / RGBA or HSL / HSLA
type = match[1];

View file

@ -66,6 +66,9 @@ test('Creating Colors', function() {
equals(new Color('#ff0000'), new Color(1, 0, 0),
'Color from hex string');
equals(new Color('#ff000099'), new Color(1, 0, 0, .6),
'Color from hex code with alpha');
equals(new Color('rgb(255, 0, 0)'), new Color(1, 0, 0),
'Color from rgb() string');