0

I have two variables but I don't know how to subtract red from white.

I tried ParseInt method to converting them to decimal and calculate and again convert to hex but it gives me a value that I can't use as color , it should give me an aqua color but because of invalid output I'm getting white background

let white = parseInt("FFFFFF",16);
let red = parseInt("FF0000",16);
let res = (white-red).toString(16);
let box = document.getElementById("mybox");
box.style.BackgroundColor = `#${res}`;
IhateReact
  • 43
  • 6
  • 1
    `let res = (white-red).toString(16).padStart(6, '0');` – Bravo Aug 13 '21 at 12:36
  • @Bravo what is `padStart` – IhateReact Aug 13 '21 at 12:37
  • https://stackoverflow.com/questions/9005917/how-to-subtract-a-color-from-another – Ben Aug 13 '21 at 12:38
  • 2
    The hex notation for colours uses two hex digits for each of the red, green and blue component of a colour. You should separate them and do calculations on each component. – axiac Aug 13 '21 at 12:38
  • 1
    [image processing - subtract one color from another in RGB color space - Stack Overflow](https://stackoverflow.com/questions/20935859/subtract-one-color-from-another-in-rgb-color-space) – Andreas Aug 13 '21 at 12:43

1 Answers1

1

You need to make the color 6 digits, by padding at the start with zeros

you can use the string method padStart for this

let white = parseInt("FFFFFF",16);
let red = parseInt("FF0000",16);
let res = (white-red).toString(16).padStart(6, '0');
console.log(`#${res}`)
Bravo
  • 6,022
  • 1
  • 10
  • 15