0

I have a bit of a problem that I am encountering with trying to convert a colour from a hex string into an integer value.

The reason that I am trying to achieve this, is that I am reading from a JSON that feeds in hex values that are then read by Pixi and standard Canvas elements to then give them their colours.

Now this will read and convert all my colours correctly until it hits one that starts with a 0 or for example 'black' which is only made up of 0's

parseInt("00aaa4", 16);//43684

This becomes an invalid number to be read by my canvas elements. Where as

parseInt("10aaa4", 16); //1092260

Is valid and will work fine. I am not sure if there is a simple work around for this problem. Tried looking for some NPM modules but they all give the same issue.

Thanks for the help.

factordog
  • 599
  • 5
  • 24
  • What do you expect this `00aaa4` to be when converted? – Adrian Dec 08 '16 at 07:06
  • Well thats the thing I dont know what it will be, I know that it breaks and defaults to pixi black when a colour doesnt work or cant be found. So for example if i did a parseInt on 000000 it returns 0. From my understanding that is incorrect – factordog Dec 08 '16 at 07:18

1 Answers1

2

There are 2 ways to mark a number's type. Putting 0x before it makes it a hexadecimal number, but 0 makes it octal.

When you try to convert the number to decimal, try to put a 0x before it, so it's not mistaken for an octal number.

Bálint
  • 4,009
  • 2
  • 16
  • 27
  • From what I know 0x isnt valid for certain canvas elements, I know its fine for pixi, but for normal canvas? Or are you saying make the string an 0x? and the convert to decimal? – factordog Dec 08 '16 at 06:58
  • Adding 16 as the radix to parseInt he is explicitly saying the number is hexadecimal – phobia82 Dec 08 '16 at 06:58
  • 1
    @factordog just do `parseInt("0x" + yourColor, 16)` – Bálint Dec 08 '16 at 06:59
  • Okay but for example parseInt("0x00aaa4", 16); will still return 43684 which will still leave it throwing an invalid colour value – factordog Dec 08 '16 at 07:02
  • what are valid color values for pixijs? – manonthemat Dec 08 '16 at 07:05
  • from my understanding its type number 0x?????? or a decimal colour value of 7+ numbers. From what I have read it cant take a #?????? or a rgb colour value. Has to be a number – factordog Dec 08 '16 at 07:10
  • Okay so I have taken your method, and then to accomodate for standard canvas I am using http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript This allows me to then change the number value to a valid canvas value with correct hex if I need it. Most of my project is using Pixi which is why majority of it will be a number colour. So now I will use decimalToHex(d, padding) which is an answer further down and this will create a valid hex value for canvas – factordog Dec 08 '16 at 08:51