From a8f78859cb51a74088fb23c9f27958b0ae5fbc23 Mon Sep 17 00:00:00 2001 From: PeterLazar Date: Fri, 5 Oct 2018 20:14:20 +0200 Subject: [PATCH] Add hexadecimal with alpha color parsing Closes #1468 --- src/style/Color.js | 20 ++++++++++++-------- test/tests/Color.js | 3 +++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/style/Color.js b/src/style/Color.js index 8717ede4..bd7f602b 100644 --- a/src/style/Color.js +++ b/src/style/Color.js @@ -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]; diff --git a/test/tests/Color.js b/test/tests/Color.js index c571bb0e..f8afec52 100644 --- a/test/tests/Color.js +++ b/test/tests/Color.js @@ -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');