Home > Software > hex2rgb Javascript

hex2rgb Javascript

January 14th, 2010

While experimenting with canvas tag today I needed a good way to take a hex value and convert it to RGBA. I went searching and found some solutions, but nothing that really seemed complete. I wanted a single function that didn’t call eval or pollute the environment with globals… Maybe I could have looked harder but here is what I came up with.

I know hex values don’t include the alpha value in rgba – this function gets you the RGB values so you can mix in the alpha value.

Update:
Duncan posted this solution that is much better than mine!

Software

  1. January 15th, 2010 at 15:13 | #1

    One thing that can really simplify your implementation is understanding the entire signature of the parseInt method.

    Specifically, the 2nd, optional parameter is the radix of the parse. By passing 16 as the radix, you get automatic hex string parsing.

    I created a squished-down version that utilizes this signature along with eliminating subString expressions by utilizing captures in the regular expression.

    http://gist.github.com/278311
    Duncan Beevers´s last blog ..Cookie Path Handling Inconsistencies My ComLuv Profile

  2. January 15th, 2010 at 17:38 | #2

    Ah man that is way better than my implementation!

  1. No trackbacks yet.
CommentLuv Enabled

Comments links could be nofollow free.