Skip to content

Commit

Permalink
Support #RGBA, #RRGGBBAA hex colors
Browse files Browse the repository at this point in the history
  • Loading branch information
zbjornson authored and chearon committed Nov 16, 2017
1 parent d1b9d19 commit e34fcb3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
40 changes: 38 additions & 2 deletions src/color.cc
Expand Up @@ -550,6 +550,20 @@ rgba_from_rgb(uint8_t r, uint8_t g, uint8_t b) {
return rgba_from_rgba(r, g, b, 255);
}

/*
* Return rgba from #RRGGBBAA
*/

static int32_t
rgba_from_hex8_string(const char *str) {
return rgba_from_rgba(
(h(str[0]) << 4) + h(str[1]),
(h(str[2]) << 4) + h(str[3]),
(h(str[4]) << 4) + h(str[5]),
(h(str[6]) << 4) + h(str[7])
);
}

/*
* Return rgb from "#RRGGBB".
*/
Expand All @@ -563,6 +577,20 @@ rgba_from_hex6_string(const char *str) {
);
}

/*
* Return rgba from #RGBA
*/

static int32_t
rgba_from_hex4_string(const char *str) {
return rgba_from_rgba(
(h(str[0]) << 4) + h(str[0]),
(h(str[1]) << 4) + h(str[1]),
(h(str[2]) << 4) + h(str[2]),
(h(str[3]) << 4) + h(str[3])
);
}

/*
* Return rgb from "#RGB"
*/
Expand Down Expand Up @@ -673,16 +701,22 @@ rgba_from_hsl_string(const char *str, short *ok) {
* Return rgb from:
*
* - "#RGB"
* - "#RGBA"
* - "#RRGGBB"
* - "#RRGGBBAA"
*
*/

static int32_t
rgba_from_hex_string(const char *str, short *ok) {
size_t len = strlen(str);
*ok = 1;
if (6 == len) return rgba_from_hex6_string(str);
if (3 == len) return rgba_from_hex3_string(str);
switch (len) {
case 8: return rgba_from_hex8_string(str);
case 6: return rgba_from_hex6_string(str);
case 4: return rgba_from_hex4_string(str);
case 3: return rgba_from_hex3_string(str);
}
return *ok = 0;
}

Expand All @@ -705,7 +739,9 @@ rgba_from_name_string(const char *str, short *ok) {
* Return rgb from:
*
* - #RGB
* - #RGBA
* - #RRGGBB
* - #RRGGBBAA
* - rgb(r,g,b)
* - rgba(r,g,b,a)
* - hsl(h,s,l)
Expand Down
10 changes: 10 additions & 0 deletions test/canvas.test.js
Expand Up @@ -140,6 +140,16 @@ describe('Canvas', function () {
ctx.fillStyle = 'afasdfasdf';
assert.equal('#ffffff', ctx.fillStyle);

// #rgba and #rrggbbaa
ctx.fillStyle = '#ffccaa80'
assert.equal('rgba(255, 204, 170, 0.50)', ctx.fillStyle)

ctx.fillStyle = '#acf8'
assert.equal('rgba(170, 204, 255, 0.53)', ctx.fillStyle)

ctx.fillStyle = '#BEAD'
assert.equal('rgba(187, 238, 170, 0.87)', ctx.fillStyle)

ctx.fillStyle = 'rgb(255,255,255)';
assert.equal('#ffffff', ctx.fillStyle);

Expand Down

0 comments on commit e34fcb3

Please sign in to comment.