Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Put 4 integers in the RGBA range

I have a function that puts 4 integers in the RGBA range. In other words, it takes 4 integers, puts the first 3 in the 8-bit range (0-255) (decimal don't matter) and puts the 4th number in the range of 0-1. And then it makes the fillStyle to that color. (It's important that this all happens in the function because I want to use random Math operations on the numbers)

Here's the code:

function FillColor(r,g,b,a){
    if (r > 255){r = 255;}
    if (g > 255){g = 255;}
    if (b > 255){b = 255;}
    if (a > 1){a = 1;}

    if (r < 0){r = 0;}
    if (g < 0){g = 0;}
    if (b < 0){b = 0;}
    if (a < 0){a = 0;}

    ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
}

My problem is that it looks unnecessarily long and it mainly just repeats itself. Is there a better way to do this?

like image 373
Sover the Avatar asked Aug 08 '26 09:08

Sover the


1 Answers

Try this:

function FillColor(r, g, b, a) {
  for (let i = 0; i < arguments.length; i++) {
    if (i === 3) arguments[i] = Math.min(Math.max(parseInt(arguments[i]), 0), 1);
    else arguments[i] = Math.min(Math.max(parseInt(arguments[i]), 0), 255);
  }

  ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
}
like image 157
AlTheLazyMonkey Avatar answered Aug 10 '26 22:08

AlTheLazyMonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!