Skip to content

Commit bc1a1f1

Browse files
authored
Merge pull request #988 from zbjornson/rrggbbaa
Support #RGBA, #RRGGBBAA hex colors
2 parents d1b9d19 + 10a82ec commit bc1a1f1

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

src/color.cc

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,20 @@ rgba_from_rgb(uint8_t r, uint8_t g, uint8_t b) {
550550
return rgba_from_rgba(r, g, b, 255);
551551
}
552552

553+
/*
554+
* Return rgba from #RRGGBBAA
555+
*/
556+
557+
static int32_t
558+
rgba_from_hex8_string(const char *str) {
559+
return rgba_from_rgba(
560+
(h(str[0]) << 4) + h(str[1]),
561+
(h(str[2]) << 4) + h(str[3]),
562+
(h(str[4]) << 4) + h(str[5]),
563+
(h(str[6]) << 4) + h(str[7])
564+
);
565+
}
566+
553567
/*
554568
* Return rgb from "#RRGGBB".
555569
*/
@@ -563,6 +577,20 @@ rgba_from_hex6_string(const char *str) {
563577
);
564578
}
565579

580+
/*
581+
* Return rgba from #RGBA
582+
*/
583+
584+
static int32_t
585+
rgba_from_hex4_string(const char *str) {
586+
return rgba_from_rgba(
587+
(h(str[0]) << 4) + h(str[0]),
588+
(h(str[1]) << 4) + h(str[1]),
589+
(h(str[2]) << 4) + h(str[2]),
590+
(h(str[3]) << 4) + h(str[3])
591+
);
592+
}
593+
566594
/*
567595
* Return rgb from "#RGB"
568596
*/
@@ -673,16 +701,22 @@ rgba_from_hsl_string(const char *str, short *ok) {
673701
* Return rgb from:
674702
*
675703
* - "#RGB"
704+
* - "#RGBA"
676705
* - "#RRGGBB"
706+
* - "#RRGGBBAA"
677707
*
678708
*/
679709

680710
static int32_t
681711
rgba_from_hex_string(const char *str, short *ok) {
682712
size_t len = strlen(str);
683713
*ok = 1;
684-
if (6 == len) return rgba_from_hex6_string(str);
685-
if (3 == len) return rgba_from_hex3_string(str);
714+
switch (len) {
715+
case 8: return rgba_from_hex8_string(str);
716+
case 6: return rgba_from_hex6_string(str);
717+
case 4: return rgba_from_hex4_string(str);
718+
case 3: return rgba_from_hex3_string(str);
719+
}
686720
return *ok = 0;
687721
}
688722

@@ -705,7 +739,9 @@ rgba_from_name_string(const char *str, short *ok) {
705739
* Return rgb from:
706740
*
707741
* - #RGB
742+
* - #RGBA
708743
* - #RRGGBB
744+
* - #RRGGBBAA
709745
* - rgb(r,g,b)
710746
* - rgba(r,g,b,a)
711747
* - hsl(h,s,l)

test/canvas.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,16 @@ describe('Canvas', function () {
140140
ctx.fillStyle = 'afasdfasdf';
141141
assert.equal('#ffffff', ctx.fillStyle);
142142

143+
// #rgba and #rrggbbaa
144+
ctx.fillStyle = '#ffccaa80'
145+
assert.equal('rgba(255, 204, 170, 0.50)', ctx.fillStyle)
146+
147+
ctx.fillStyle = '#acf8'
148+
assert.equal('rgba(170, 204, 255, 0.53)', ctx.fillStyle)
149+
150+
ctx.fillStyle = '#BEAD'
151+
assert.equal('rgba(187, 238, 170, 0.87)', ctx.fillStyle)
152+
143153
ctx.fillStyle = 'rgb(255,255,255)';
144154
assert.equal('#ffffff', ctx.fillStyle);
145155

0 commit comments

Comments
 (0)